f 1(f 2(f 3(f 4(x)))のようなcompseを実現する.
960 ワード
関数があると仮定します
[f1, f2, f3, f4]
f 1(f 2(f 3(f 4(x)))))function compose(...funcs) {
if(funcs.length === 0) {
return args => args;
}
return funcs.reduce((acc, current) => {
return (...args) => acc(current(...args));
});
}
f 4(f 3(f 2(f 1(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);