-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
026.curry #26
Comments
// 使用递归函数调用
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...nextArgs) => curried(...args, ...nextArgs);
};
} |
// 使用闭包
function curry(fn) {
let len = fn.length
let curArgs = []
return function curried(...args) {
curArgs.push(...args)
if (curArgs.length >= len) {
const res = fn(...curArgs)
curArgs = [] // 注意要清空
return res
} else {
return curried
}
};
}; |
考虑 this 绑定function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function (...args2) {
return curried.apply(this, args.concat(args2));
}
}
};
} // 使用 bind
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return curried.bind(this, ...args);
};
}; |
不定参数function sum(...args) {
return args.reduce((pre, cur) => pre + cur, 0)
} 使用空参数调用触发函数 // 使用闭包
function curry(fn) {
let allArgs = []
return function curried(...args) {
if (args.length === 0) {
const res = fn(...allArgs);
allArgs = []
return res
}
allArgs.push(...args);
return curried;
};
}; // 递归
function curry(fn) {
return function curried(...args) {
return (...nextArgs) => {
if (nextArgs.length === 0) {
return fn(...args);
}
return curried(...args, ...nextArgs);
};
};
}; |
相关题目:实现 sum 的链式调用function sum(...args) {
const arr = [...args];
function add(...rest) {
arr.push(...rest);
return add;
}
// 隐式调用,注意直接 console.log 不行
add.valueOf = add.toString = function () {
return arr.reduce((pre, cur) => pre + cur, 0)
};
return add;
}
console.log(+sum1(1)(2)(3)(10)(10, 20))
console.log('sum:' + sum1(1)(2)(3)(10)(10, 20)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: