A curried function takes a single argument and returns another function that takes the next argument until it can evaluate to a result.
Last active
July 30, 2017 17:00
-
-
Save mateuszsokola/623478f6c8c234e70a4f5e09e1bf3751 to your computer and use it in GitHub Desktop.
Currying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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