/curry.js Secret
Created
November 24, 2020 11:58
柯里化
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
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