Skip to content

Instantly share code, notes, and snippets.

@mateuszsokola
Last active July 30, 2017 17:00
Show Gist options
  • Save mateuszsokola/623478f6c8c234e70a4f5e09e1bf3751 to your computer and use it in GitHub Desktop.
Save mateuszsokola/623478f6c8c234e70a4f5e09e1bf3751 to your computer and use it in GitHub Desktop.
Currying

Currying

A curried function takes a single argument and returns another function that takes the next argument until it can evaluate to a result.

Example implementation

const _ = require('lodash');
function add(a, b) {
return a + b;
}
const _add = _.curry(add);
_add(1); // function
_add(1)(2); // 3
_add(1)(2)(3); // TypeError
_add(_add(1)(2), 3) // 6
// Infinite currying
function addInfinite (total) {
var sum = function (...nums) {
const _sum = nums.reduce((acc, num) => acc + num, total);
return addInfinite(_sum);
}
sum.valueOf = function () {
return total;
};
return sum;
}
addInfinite(1); // { [Number: 1] valueOf: [Function] }
addInfinite(1)(2); // { [Number: 3] valueOf: [Function] }
addInfinite(1)(2)(3); // { [Number: 6] valueOf: [Function] }
0 + addInfinite(1)(2)(3); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment