Appearance
compose
本节目标:理解“compose”的核心思路,并能把它用于实际开发或面试表达。 如果一个函数需要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并一个函数;
src\redux\compose.js
functionadd1(str){return '1' +
str;
}
functionadd2(str){return '2' +
str;
}
functionadd3(str){return '3' +
str;
}
functioncompose(...funcs){return function
(args){for
(leti =
funcs.length-
1;i \>=
0;i--){args =
funcs[i](args); `}`
`return`
args;}
}function compose(...funcs) {
return funcs.reduce((a, b) => (...args) => a(b(...args)));
}第一次:a=add3,b=add2;
- 返回一个函数:
(...args)=\>add3(add2(...args)); - 这个返回的函数将作为
reduce的第一个参数;
第二次:a为一个函数,即上次迭代返回值(...args)=\>add3(add2(...args)), b为add1;
- 返回一个函数:
(...args)=\>add3(add2((add1(...args)))))
let fn =
compose(add3,add2,add1);
letresult =
fn('zhufeng');
console.log(result);链式调用
functioncompose(...funcs){return
funcs.reduce((a,b)=\>
(...args)=\>
a(b(...args)));
}
letpromise =
(next)=\> action =\> {
console.log('promise');next(action);
};
letthunk =
(next)=\> action =\> {
console.log('thunk');next(action);
};
letlogger =
(next)=\> action =\> {
console.log('logger');next(action);
};
letchain =
[promise,thunk,logger];
letcomposed =
compose(...chain)
letdispatch = () =\> {
console.log('原始的
dispatch');
}
letnewDispatch =
composed(dispatch);
newDispatch({type: "add" });
