Sub topic 3
Currying and Advanced Techniques
This chapter assumes you already know closures, higher-order functions, and pipe/compose from the earlier chapters. It covers the remaining tools briefly.
Currying and Partial Application
Currying turns a function of several arguments into a chain of functions that each take one argument. Partial application fixes some arguments up front and returns a function that takes the rest.
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1)(2)(3)); // 6
console.log(add3(1, 2)(3)); // 6
const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2); // partial application
console.log(double(21)); // 42A common error is currying a function that has default or rest parameters. fn.length does not count them, so curry calls the function too early.
Point-Free Style
Point-free style defines a function by composing other functions, without naming its argument. For example, const shout = pipe(trim, toUpper) replaces (s) => toUpper(trim(s)). This style reads well for short pipelines. Long ones are harder to debug.
Recursion, Memoization, and Laziness
const sum = ([head, ...tail]) =>
head === undefined ? 0 : head + sum(tail);
console.log(sum([1, 2, 3, 4])); // 10
const memoize = (fn) => {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
};
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
console.log(fib(50)); // 12586269025
function* naturals() {
let n = 1;
while (true) yield n++;
}
function* take(count, iterable) {
if (count <= 0) return;
for (const x of iterable) {
yield x;
if (--count <= 0) return;
}
}
console.log([...take(3, naturals())]); // [ 1, 2, 3 ]Containers and Maybe
A functor is a container with a map method that applies a function to the value inside it. Maybe skips map when the value is null or undefined.
const Maybe = (value) => ({
map: (fn) => (value == null ? Maybe(null) : Maybe(fn(value))),
getOrElse: (fallback) => (value == null ? fallback : value)
});
console.log(Maybe({}).map((u) => u.address).map((a) => a.city).getOrElse('Unknown')); // UnknownTrade-offs and Libraries
| Benefit | Cost |
|---|---|
| Predictable, testable functions | Extra allocations from copying |
| Reusable small pieces | Stack traces through many wrappers |
| Fewer null checks | Unfamiliar style for some teams |
Ramda provides auto-curried utilities. Lodash/fp and Immer cover immutable updates. Use them where they make code clearer, not everywhere.
Exercise
Why does curry((a, b = 1) => a + b) call the function after receiving only one argument?
Show answer
fn.length counts only the parameters before the first default value, so it is 1. The curried function sees one argument as enough and calls fn immediately.