Last active
April 18, 2017 13:54
-
-
Save YozhEzhi/5053806ed64a8580b46563fc8d2d224c to your computer and use it in GitHub Desktop.
ES6 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 curry = fn => { | |
const arity = fn.length; | |
return (...args) => { | |
if (args.length >= arity) { | |
return fn(...args); | |
} else { | |
return (...secondArgs) => { | |
return fn(...[...args, ...secondArgs]); | |
} | |
} | |
} | |
}; | |
const sum = (a, b) => a + b; | |
const addOne = curry(sum)(1); | |
const addNine = curry(sum)(9); | |
addOne(4); // 5 | |
addNine(1); // 10 | |
// ======== // | |
function partialApplication(fn, ...args) { | |
if (args.length === fn.length) return fn(...args); | |
return partialApplication.bind(this, fn, ...args); | |
} | |
partialApplication(sum, 1, 2); // 3 | |
partialApplication(sum)(1)(2); // 3 | |
partialApplication(sum)(1, 2); // 3 | |
partialApplication(sum, 1)(2); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment