时间:2021-2-1 Mon
done
实现sum(1)(2)(3)(4).sumOf();
:::success
实现 sum 函数使得以下表达式的值正确
sum(1, 2, 3).sumOf(); //6
sum(2, 3)(2).sumOf(); //7
sum(1)(2)(3)(4).sumOf(); //10
sum(2)(4, 1)(2).sumOf(); //9
:::
区别: sumOf终止, 参数数量不限
arguments.slice() is not a funtion
正确写法:
⚠️ return fn应放在底部
⚠️ fn.prototype.sumOf 错误, fn.sumOf正确
function sum() {
let args = Array.prototype.slice.call(arguments)
let sum = args.reduce((a, c) => a + c, 0);
function fn () {
let args2 = Array.prototype.slice.call(arguments);
sum += args2.reduce((a, c) => a + c, 0);
return fn
}
fn.sumOf = function () {
return sum;
}
return fn; // 注意, 必须放在底部
}
console.log(sum(1, 2, 3).sumOf()) // 6
console.log(sum(1, 2, 3)(4, 5).sumOf()) // 15
console.log(sum(2, 3)(2).sumOf()) // 7
console.log(sum(1)(2)(3)(4).sumOf()) // 10
console.log(sum(2)(4, 1)(2).sumOf()) // 9
实现curriedSum(1)(2)(3)
:::success
//1.手写函数柯里化
function curry(func) {
//此处补全
}
function sum(a, b, c) {
return a + b + c;
}
let curriedSum = curry(sum);
alert(curriedSum(1, 2, 3)); // 6, still callable normally
alert(curriedSum(1)(2, 3)); // 6, currying of 1st arg
alert(curriedSum(1)(2)(3)); // 6, full currying
:::
区别:参数固定, 参数传入顺序无关
实现
//1.手写函数柯里化
function curry(func, args) {
const n = func.length;
args = args || [];
return function (...rest) {
var _args = [...args, ...rest];
if (_args.length < n) {
return curry.call(this, func, _args);
} else {
return func.apply(this, _args);
}
}
}
function sum(a, b, c) {
return a + b + c;
}
let curriedSum = curry(sum);
console.log(curriedSum(1, 2, 3)); // 6, still callable normally
console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg
console.log(curriedSum(1)(2)(3)); // 6, full currying
// 6
// 6
// 6
优化, 采用隐参获取参数
涉及函数参数
//1.手写函数柯里化
function curry(func) {
const n = func.length;
let args = Array.prototype.slice.call(arguments).slice(1);
return function () {
var _args = args.concat(Array.prototype.slice.call(arguments));
if (_args.length < n) {
return curry.call(this, func, ..._args);
} else {
return func.apply(this, _args);
}
}
}
function sum(a, b, c) {
return a + b + c;
}
let curriedSum = curry(sum);
console.log(curriedSum(1, 2, 3)); // 6, still callable normally
console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg
console.log(curriedSum(1)(2)(3)); // 6, full currying
// 6
// 6
// 6