关于javascript:实现一个如-f1f2f3f4x-的-compose

34次阅读

共计 685 个字符,预计需要花费 2 分钟才能阅读完成。

假如有函数

[f1, f2, f3, f4]

f1(f2(f3(f4(x))))

function compose(...funcs) {if(funcs.length === 0) {return args => args;}
  return funcs.reduce((acc, current) => {return (...args) => acc(current(...args));
  });
}

f4(f3(f2(f1(x))))

function compose(...funcs) {if(funcs.length === 0) {return args => args;}
  return funcs.reduce((acc, current) => {return (...args) => current(acc(...args));
  });
}

经典题型测试

function add(a, b = 1) {return a + b;}
 
function square(a) {return a*a;}
 
function plusOne(a) {return a + 1;}
 
function compose(...funcs) {if(funcs.length === 0) {return args => args;}
  return funcs.reduce((acc, current) => {return (...args) => acc(current(...args));
  });
}
 
var addSquareAndPlusOne = compose(add, square, plusOne);
 
addSquareAndPlusOne(1, 2);

正文完
 0