实现柯里化
柯里化(Currying) 在JavaScript是一个常用的技巧。
请实现一个curry()方法,接受一个function然后返回一个柯里化过后的function。
For Example
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
const curriedJoin = curry(join)
curriedJoin(1, 2, 3) // '1_2_3'
curriedJoin(1)(2, 3) // '1_2_3'
curriedJoin(1, 2)(3) // '1_2_3'
Answer
function curry(fn, ...args) {
return fn.length > args.length
? (..._args) => curry(fn, ...args, ..._args)
: fn(...args);
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`;
};
const curriedJoin = curry(join);
console.log(curriedJoin(1, 2, 3, 4));
console.log(curriedJoin(1)(2, 3));
console.log(curriedJoin(1, 2)(3));
基于上面的要求,请实现带占位符号的柯里化
For Example
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
const curriedJoin = curry(join)
const _ = curry.placeholder
curriedJoin(1, 2, 3) // '1_2_3'
curriedJoin(_, 2)(1, 3) // '1_2_3'
curriedJoin(_, _, _)(1)(_, 3)(2) // '1_2_3'