Skip to content

Instantly share code, notes, and snippets.

@shapled

shapled/curry.js Secret

Created November 24, 2020 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shapled/989e778e75335d959d011c51547b6725 to your computer and use it in GitHub Desktop.
Save shapled/989e778e75335d959d011c51547b6725 to your computer and use it in GitHub Desktop.
柯里化
function curry(f, params_count) {
if ([0, 1].includes(params_count)) return f;
let result_function = f;
for (let i = 1; i < params_count; i++) {
const last_result_function = result_function
result_function = function(...params) {
return function(...params2) {
params2 = params2.concat(params)
return last_result_function(...params2)
}
}
}
return result_function;
}
function add1(a, b) { return a + b }
function add2(a, b, c) { return a + b + c }
const curriedAdd1 = curry(add1, 2);
const curriedAdd2 = curry(add2, 3);
console.log(curriedAdd1(1)(2)); // 3
console.log(curriedAdd1(3)(2)); // 5
const t = curriedAdd1(1)
console.log(t(2)); // 3
console.log(t(3)); // 4
console.log(curriedAdd2(1)(2)(3)); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment