闭包的应用

132 阅读1分钟
函数柯里化

分析下reduce数组的迭代方法

/* 
	index 标识item的下标
*/
[1,2,3].reduce((result,item,index) => {
    console.log(result,item,index);
    return result+item
})
//=>1 2 1
//=>3 3 2

/*----*/
[1,2,3].reduce((result,item,index) => {
    console.log(result,item,index);
    return result+item
},0);

//=> 0 1 0
//=> 1 2 1
//=> 3 3 2
/*
	思想 1.柯里化就是收集参数
		2.大函数调用返回小函数进行收集
		3.然后通过函数console.log()会转换成字符串 重写[Symbol.toPrimitive/valueof/tostring]中的一个返回结果
		
*/
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 */

/*根据上面写柯里化函数*/
/*--方法一--*/
const curring = function (){
    let data = [];
    //curring(); 指向之后 add()都是走这个
    return function add(...args){
        //因为函数console.log()会转换成字符串 所以重写[Symbol.toPrimitive/valueof/tostring]都可以
        add[Symbol.toPrimitive] = () => data.reduce((result, item) => result + item);
        data = data.concat(args);
        return add
    }
}
/*--方法二--*/
const curring = function curring() {
    let params = [];
    const add = (...args) => {
        params = params.concat(args);
        return add;
    };
    add[Symbol.toPrimitive] = () => params.reduce((result, item) => result + item);
    return add;
};

compose

在函数式编程当中有一个很重要的概念就是函数组合, 实际上就是把处理数据的函数像 管道一样连接起来, 然后让数据穿过管道得到最终的结果。 例如:

const add1 = (x) => x + 1;

const mul3 = (x) => x * 3;

const div2 = (x) => x / 2;

div2(mul3(add1(add1(0)))); //=>3

const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;

const compose = function (...args){
    return function (num){
        return args.reduceRight((result, item) => {
            return item(result)
        },num)
    }
}

//大函数执行返回小函数
console.log(compose(div2,mul3,div2)(2))	//=>1.5