实现一个如 f1(f2(f3(f4(x)))) 的 compose

假设有函数

[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);

你可能感兴趣的:(javascript)