以下是需要組合并為我們提供輸出的三個函式30:
const add = (a) => a 10;
const mul = (a) => a * 10;
const divide = (a) => a / 5;
// How to implement `compositionFunction`?
compositionFunction(add, mul, divide)(5);
//=> 30
預期輸出是30因為:
5 10 = 15
15 * 10 = 150
150 / 3 = 30
uj5u.com熱心網友回復:
像這樣的東西
const add = (a) => a 10 ;
const mul = (a) => a * 10 ;
const divide = (a) => a / 5 ;
// How to use this function -----
const customComposeFn = (...f) => v => f.reduce((res, f) => f(res), v)
console.log(customComposeFn(add, mul, divide)(5));
uj5u.com熱心網友回復:
函陣列合有兩種風格:
- 從左到右的函陣列合又名
pipe - 從右到左的函陣列合又名
compose
這是一個遞回實作,只是為了好玩:
這假設至少有兩個函式要組合
const compose = (...fn) => {
const [[f, g], x] = [fn.slice(-2), fn.slice(0, -2)];
const h = a => f(g(a));
return x.length ? compose(...x, h) : h;
}
const pipe = (...fn) => {
const [f, g, ...x] = fn;
const h = a => g(f(a));
return x.length ? pipe(h, ...x) : h;
}
我們試試吧:
const foo = x => x 'foo';
const bar = x => x 'bar';
const baz = x => x 'baz';
pipe(foo, bar, baz)('');
//=> 'foobarbaz'
compose(foo, bar, baz)('');
//=> 'bazbarfoo'
uj5u.com熱心網友回復:
const add = (a) => a 10;
const mul = (a) => a * 10;
const divide = (a) => a / 5;
const customComposeFn = (...fn) => {
return function (arg) {
if (fn.length > 0) {
const output = fn[0](arg);
return customComposeFn(...fn.splice(1))(output);
} else {
return arg;
}
};
};
const res = customComposeFn(add, mul, divide)(5);
console.log(`res`, res);
uj5u.com熱心網友回復:
這是我要做的:
function customComposeFn(...funcs) {
return function(arg) {
let f, res = arg;
while (f = funcs.shift()) {
res = f(res)
}
return res;
}
}
const add = a => a 10;
const mul = a => a * 10;
const divide = a => a / 5;
// How to use this function -----
console.log(customComposeFn(add, mul, divide)(5));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448699.html
標籤:javascript 函数式编程 功能组合
上一篇:在洗掉重復值的同時轉換陣列布局
