Careeroza
Currying & Partial Application
Currying
Example
Currying turns f(a, b, c) into f(a)(b)(c), so you can create specialised functions:
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
console.log(double(10), triple(10));
const addGst = (rate) => (price) => +(price * (1 + rate)).toFixed(2);
const gst18 = addGst(0.18);
console.log([100, 250].map(gst18));Output
20 30 [ 118, 295 ]
A Generic curry Helper
Example
const curry = (fn) =>
function curried(...args) {
return args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
};
const volume = curry((l, w, h) => l * w * h);
console.log(volume(2)(3)(4), volume(2, 3)(4), volume(2, 3, 4));Output
24 24 24