The 11th question of BEF.dev. Link is here what is Composition? create a pipe()
const times = (y) => (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) => (x) => x - y
const divide = (y) => (x) => x / y
pipe([
times(2),
plus(3),
times(4)
])
// (x * 2 + 3) * 4
pipe([
times(2),
subtract(3),
divide(4)
])
// (x * 2 - 3) / 4
For this question, because the parameter that pipe takes in is an array, so we can use a for loop or an Array’s api to solve it.
And we should notice that, the describe of this question notes that the functions passed to pipe() will all accept 1 argument, so it’s a function currying here.
function pipe(funcs) {
return function(arg) {
let result = arg
for (func of funcs) {
result = func.call(this, result)
}
return result
}
}
Code above is a solution which use for loop, we should firstly return a function and take in an arg as parameter, and this arg represents the x. Then, we can use for loop first, and we let result equals to arg, then we use for of to iterate through funcs and func here is each method of funcs.
Then we can simply call func and push in result as its’ parameter, so we get the value from func this time and we need to assign it to result. Finally return result.
function pipe(funcs) {
return function(arg) {
return funcs.reduce((result, func) => {
return func.call(this, result)
}, arg)
}
}
And we can also use array’s api here, we can use reduce here, and we all know that the first parameter of reduce function is an arrow function, and there are two parameters in it, the first one is previous value of last for loop’s result, and the second one is current value, and the second parameter of reduce function is an initialize parameter. So we can pass arg as the second parameter of reduce function and we make result and func as parameter as arrow function’s parameter.
Then we can just call func here and pass result into it.
本文探讨了BEF.dev中如何使用管道操作(pipe())结合函数组合(如functioncurrying)和Array的API(reduce)来处理数组参数的函数调用。作者提供了两种解决方案,一种是使用for循环,另一种是利用reduce方法简化过程。

被折叠的 条评论
为什么被折叠?



