天天看点

函数式编程:纯函数&柯里化&组合函数

函数式编程:纯函数&柯里化&组合函数

    • 纯函数
    • 函数的柯里化
    • 组合函数

纯函数

  • 相同的输入值,产生相同的输出
  • 在函数的执行过程中,不能产生副作用。
  • 不能对传入的参数进行修改,不依赖上层作用域内的数据。

函数的柯里化

函数柯里化:详细函数柯里化介绍

相较于链接文章内对柯里化函数的实现,感觉这个代码更容易理解一些。

function currying(fn, ...args1) {
  function curried(...args2) {
    if (args2.length >= fn.length - args1.length) {
      const arr = args2.concat(args1);
      return fn.apply(this, arr);
    } else {
      return function (...args3) {
        return curried.apply(this, args2.concat(args3));
      };
    }
  }
  return curried;
}

function add(n1, n2, n3, n4) {
  return n1 + n2 + n3 + n4;
}

var add1 = currying(add, 10);  // 100
console.log(add1(20, 30, 40)); // 100
console.log(add1(20, 30)(40)); // 100
console.log(add1(20)(30)(40)); // 100

           

组合函数

将多个函数组合起来,自动依次调用,这个过程就是对函数的组合

组合函数的实现:

function compose(...fns) {
  fns.forEach((fn) => {
    if (typeof fn !== "function") {
      throw new TypeError("exit not function params");
    }
  });
  return function (...params) {
    var index = 0;
    var result = fns.length ? fns[index].apply(this, params) : params;
    while (++index < fns.length) {
      result = fns[index].call(this, result);
    }
    return result;
  };
}

function double(num1) {
  return 2 * num1;
}

function add(num) {
  return num + 5;
}

function squire(num1) {
  return num1 * num1;
}

var fn = compose(add, double, squire);
console.log(fn(1)); // 144

           

继续阅读