1

假设有函数

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

NsNe
1.7k 声望38 粉丝

善良,学习,拼搏。不忘初心,方得始终。