Ramda

Language: JavaScript

Utility

Ramda was created to help developers write cleaner and more maintainable code using functional programming principles. Unlike other utility libraries, Ramda's functions are automatically curried and designed to be data-last, making composition simple and intuitive.

Ramda is a practical functional library for JavaScript programmers. It provides a suite of utility functions for functional programming, emphasizing immutability, currying, and composition.

Installation

npm: npm install ramda
yarn: yarn add ramda

Usage

Ramda provides functions for working with arrays, objects, strings, and functions in a functional style. Its utilities support currying, composition, and point-free programming.

Mapping over an array

import R from 'ramda';
const numbers = [1, 2, 3];
const doubled = R.map(x => x * 2, numbers);
console.log(doubled); // [2, 4, 6]

Uses `R.map` to apply a function to each element in an array.

Filtering an array

import R from 'ramda';
const numbers = [1, 2, 3, 4];
const evens = R.filter(x => x % 2 === 0, numbers);
console.log(evens); // [2, 4]

Filters elements of an array that satisfy the provided predicate function.

Function composition

import R from 'ramda';
const add1 = x => x + 1;
const double = x => x * 2;
const addThenDouble = R.compose(double, add1);
console.log(addThenDouble(3)); // 8

Composes functions so that `add1` runs first and `double` runs on its result.

Currying

import R from 'ramda';
const add = (a, b) => a + b;
const curriedAdd = R.curry(add);
const add5 = curriedAdd(5);
console.log(add5(10)); // 15

Demonstrates Ramda’s automatic currying of functions for partial application.

Deep object manipulation

import R from 'ramda';
const obj = { a: { b: 1 } };
const updated = R.assocPath(['a', 'b'], 42, obj);
console.log(updated); // { a: { b: 42 } }

Updates a nested property immutably using `assocPath`.

Lens usage

import R from 'ramda';
const user = { name: 'Alice', address: { city: 'NY' } };
const cityLens = R.lensPath(['address', 'city']);
const updatedUser = R.set(cityLens, 'LA', user);
console.log(R.view(cityLens, updatedUser)); // 'LA'

Uses Ramda lenses to focus on and update nested data in an immutable way.

Error Handling

TypeError: value.map is not a function: Ensure the input to array functions like `R.map` or `R.filter` is actually an array.
Lens operations not updating correctly: Make sure you use `R.set` to update values and `R.view` to read, since Ramda functions are immutable.

Best Practices

Use point-free style and function composition for cleaner code.

Favor immutability and avoid mutating input data.

Leverage currying and partial application to simplify reusable functions.

Use lenses for safe manipulation of nested objects.

Combine Ramda functions with native JavaScript for optimal performance and readability.