JavaScript 实现 curry
实现函数curry,该函数接受一个多元(多个参数)的函数作为参数,然后一个新的函数,这个函数 可以一次执行,也可以分多次执行。
// test
function test(a, b, c) {
console.log(a, b, c);
}
const f1 = curry(test)(1);
const f2 = f1(2);
f2(3);
curry 的意义在于能够在不完全指定函数参数的情况下运行函数,实际意义呢? 其实 curry 需要和 compose 等配合来有效果,比如配合写出 pointfree 的代码。
代码
function curry(fn) {
const ctx = this;
function inner(...args) {
if (args.length === fn.length) return fn.call(ctx, ...args);
return (...innerArgs) => inner.call(ctx, ...args, ...innerArgs);
}
return inner;
}
// test
function test(a, b, c) {
console.log(a, b, c);
}
const f1 = curry(test)(1);
const f2 = f1(2);
f2(3);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论