js 函数式编程 compose 与 curry

一,compose (组合函数)

compose 函数的作用就是组合函数,将函数串联起来执行,一个函数的输出结果是另一个函数的输入参数,一旦第 1 个函数开始执行,就会像多米诺骨牌一样推导执行了。

实现:

方式一:

使用array.reduce()方法

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

如果想要组合函数从右往左串联执行,使用reduceRight(),reduceRight() 从数组的末尾向前将数组中的数组项做累加

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

let add = x => x+5;
let multiply = y => y*10;
let division = z => z/2;

function compose() {
    let args = [].slice.call(arguments);
    return function (x) {
        return args.reduce(function(total,current){
            return current(total)
        },x)
        
    }
}

let calculate = compose(add,multiply,division);
calculate(5); //50

  

方式二:

let add = x => x+5;
let multiply = y => y*10;
let division = z => z/2;
	
function compose() {
    let arg = [].slice.call(arguments);
    return function (...args) {
        let index = 0;
        let result = arg[index](...args);
		
        while (++index < arg.length) {
            result = arg[index](result)
        }
        console.log(result);
        return result
    }
    
}	
let calculate = compose(add,multiply,division);
calculate(5);  //50

  

二,curry(柯里化)

柯里化,又称为部分求值,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回一个新的函数的技术,新函数接受余下参数并返回运算结果。
curry 主要有 3 个作用:缓存函数、暂缓函数执行、分解执行任务。

//通用柯里化函数
function curry(func) {
    // 存储已传入参数
    let _args = [];
  return function _curry () {
        if (arguments.length === 0) {
            return func.apply(this, _args);
        }
        Array.prototype.push.apply(_args, [].slice.call(arguments));
        return arguments.callee;  //返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文,这有利于匿名函数的递归或者保证函数的封装性
       // return _curry;     //这个也可以

    }
  }

  // 测试代码
function add1(a, b, c) {
    return a + b + c;
  }
  function reduce(a, b, c) {
    return a - b - c;
  }  
  let testAdd = curry(add1);
  let testReduce = curry(reduce);
  
  //参数复用,提前返回,延迟执行
  console.log(testAdd(1)(2)(3)()); //6
  console.log(testReduce(3)(2)); // f_curry(){}
  console.log(testReduce(0)());  //1

  

posted @ 2020-10-15 20:30  北巷听雨  阅读(379)  评论(0编辑  收藏  举报
返回顶端