Last active
May 2, 2022 15:56
-
-
Save AoiYamada/ae494f6b710f5bd70018a70828c083d8 to your computer and use it in GitHub Desktop.
a function to currify another function
This file contains hidden or 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
/** | |
* @param {Function} fn - The function wanted to be currified | |
* @return {Function} a currified function | |
*/ | |
function curry(fn) { | |
return curryHelper(fn); | |
} | |
// private helper, not expose to client | |
function curryHelper(fn, memory = [], ...args) { | |
const local = memory.concat(args); | |
if(local.length >= fn.length) | |
return fn(...local); | |
else | |
return curry.bind(null, fn, local); | |
} | |
/* test on browser console: | |
function test(a, b, c) { | |
console.log(a, b, c) | |
} | |
var x = curry(test)('I','am'); | |
var y1 = x('Yamada'); | |
var y2 = x('Aoi'); | |
// I am Yamada | |
// I am Aoi | |
var m = curry(test)('I'); | |
var n1 = m('love'); | |
var n2 = m('also love'); | |
var o1 = n1('cats'); | |
var o2 = n1('dogs'); | |
var o3 = n2('*****'); | |
// I love cats | |
// I love dogs | |
// I also love ***** | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment