目录
1、功能函数
-
- 1、功能函数
- 2、第一种 compose 函数
- 3、第二种 compose 函数
- 4、调用
let fn1 = function (x) { return x + 10; }; let fn2 = function (x) { return x * 10; }; let fn3 = function (x) { return x / 10; };2、第一种 compose 函数
function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1){ return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); };3、第二种 compose 函数
function compose(...funcs) { // funcs:传递的函数集合 return function proxy(...args) { // args:第一次调用函数传递的参数集合 let len = funcs.length; if(len === 0) { // 一个函数都不需要执行,直接返回 args return args; }; if(len === 1) { // 只需要执行一个函数,直接返回 args return funcs[0](...args); }; return funcs.reduce((x, y) => { return typeof x === "function" ? y(x(...args)) : y(x); }); }; };4、调用
// 第三种调用方式(需要配合 compose 函数调用) compose()(5); compose(fn1)(5); compose(fn1, fn2)(5); compose(fn1, fn2, fn1, fn3)(5); // 第二种调用方式 let x = fn1(5); x = fn2(x); x = fn1(x); x = fn3(x); console.log(x); // 第一种调用方式 console.log(fn3(fn1(fn2(fn1(5))))); // => ((5+10)*10+10)/10 =>16