柯理化函数

162 阅读1分钟

1、柯理化函数 curring:预先处理的思想「利用闭包,保存私有上下文中的一些信息,供其下级上下文中调取使用,也就是我们把一些信息先预先保存下来,后期让其下级上下文使用」 => 大函数执行返回小函数

//下面这个就是柯里化思想
const fn = (...params) => {
    // 闭包:params -> [1,2]
    return (...args) => {
        return params.concat(args).reduce((total, item) => {
            return total + item;
        });
    };
};
fn(1, 2)(3); 

2、

function fn() {}  //定义一个函数fn
fn.toString = function () {
    console.log('一定调我了');
    return 'OK';
};
// console.log(fn); //->fn.toString
alert(fn); //->fn.toString

(1)定义一个函数,我们用console.log()调用的时候,一定会调用fn.toString()方法;但是输出的形式是f fn(){} 这个是console.log的一个机制

(2)alert的时候,输出的形式是这样的

3、编写一个函数实现下面的代码

(1)第一种方案是利用console.log的机制

 const curring = () => {
    let arr = [];
    const add = (...params) => {
        // 把每一次执行ADD方法传递的值都保留下来
        arr = arr.concat(params);
        return add;
    };
    add.toString = () => {
        // 输出ADD会调用其toString方法
        return arr.reduce((total, item) => total + item);
    };
    return add;
};

每次执行add都会返回一个函数,再结合console.log的机制,我们再最后输出的时候,会调用这个返回的函数的toString方法;利用柯里化的思想,我们把arr放在最外层的函数里,让我们定义的add函数的上级作用域是curring函数即可;

let add = curring();
let res = add(1)(2)(3);
console.log(res); //->6

add = curring();
res = add(1, 2, 3)(4);
console.log(res); //->10

add = curring();
res = add(1)(2)(3)(4)(5);
console.log(res); //->15 

(2)定义调用几次

  const curring = n => {
  let arr = [],
      index = 0;
  const add = (...params) => {
      index++;
      arr = arr.concat(params);
      if (index === n) {
          return arr.reduce((total, item) => total + item);
      }
      return add;
  };
  return add;
  };
  
  

    let add = curring(3);
    let res = add(1)(2)(3);
    console.log(res); //->6

    add = curring(2);
    res = add(1, 2, 3)(4);
    console.log(res); //->10

    add = curring(5);
    res = add(1)(2)(3)(4)(5);
    console.log(res); //->15