okboy5555 / Learning-notes

9 stars 1 forks source link

JS实现函数无限操作&& 柯里化 #6

Open okboy5555 opened 4 years ago

okboy5555 commented 4 years ago

执行operator的时候如果最后不是以()结尾(如operator (1)(2)),则这个结果会一直缓存到闭包里。如果下次直接operator (3)(4)的话结果是10.因为他会累加之前的结果。如果你不想这样,那可以通过加()消费缓存的结果

operator (1)(2)(3) => f(x)...;

operator (1)(2)(3)() => 6;
okboy5555 commented 4 years ago
const operator = (...args) => {
        let params = [...args]
        const _add = (...args1) => {
          console.log('args1', args1)
          params = [...params, ...args1]
          console.log(params)
          if (args1.length > 0) {
            return _add
          } else {
            return params.reduce((a, b) => a + b, 0)
          }
        }
        return _add
      }
      console.log(operator(1)(2)(3)())
okboy5555 commented 4 years ago

补充柯里化

let currying = (fn, ...args) => {
  return fn.length > args.length
    ? (...arguments) => currying(fn, ...args, ...arguments)
    : fn(...args);
};

let addSum = (a, b, c) => a + b + c;
let add = currying(addSum);
console.log(add(1)(2)(3));
console.log(add(1, 2)(3));
console.log(add(1, 2, 3));