时间: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正确

  1. function sum() {
  2. let args = Array.prototype.slice.call(arguments)
  3. let sum = args.reduce((a, c) => a + c, 0);
  4. function fn () {
  5. let args2 = Array.prototype.slice.call(arguments);
  6. sum += args2.reduce((a, c) => a + c, 0);
  7. return fn
  8. }
  9. fn.sumOf = function () {
  10. return sum;
  11. }
  12. return fn; // 注意, 必须放在底部
  13. }
  14. console.log(sum(1, 2, 3).sumOf()) // 6
  15. console.log(sum(1, 2, 3)(4, 5).sumOf()) // 15
  16. console.log(sum(2, 3)(2).sumOf()) // 7
  17. console.log(sum(1)(2)(3)(4).sumOf()) // 10
  18. 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. //1.手写函数柯里化
  2. function curry(func, args) {
  3. const n = func.length;
  4. args = args || [];
  5. return function (...rest) {
  6. var _args = [...args, ...rest];
  7. if (_args.length < n) {
  8. return curry.call(this, func, _args);
  9. } else {
  10. return func.apply(this, _args);
  11. }
  12. }
  13. }
  14. function sum(a, b, c) {
  15. return a + b + c;
  16. }
  17. let curriedSum = curry(sum);
  18. console.log(curriedSum(1, 2, 3)); // 6, still callable normally
  19. console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg
  20. console.log(curriedSum(1)(2)(3)); // 6, full currying
  21. // 6
  22. // 6
  23. // 6

优化, 采用隐参获取参数
涉及函数参数

  1. //1.手写函数柯里化
  2. function curry(func) {
  3. const n = func.length;
  4. let args = Array.prototype.slice.call(arguments).slice(1);
  5. return function () {
  6. var _args = args.concat(Array.prototype.slice.call(arguments));
  7. if (_args.length < n) {
  8. return curry.call(this, func, ..._args);
  9. } else {
  10. return func.apply(this, _args);
  11. }
  12. }
  13. }
  14. function sum(a, b, c) {
  15. return a + b + c;
  16. }
  17. let curriedSum = curry(sum);
  18. console.log(curriedSum(1, 2, 3)); // 6, still callable normally
  19. console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg
  20. console.log(curriedSum(1)(2)(3)); // 6, full currying
  21. // 6
  22. // 6
  23. // 6