create a pipe【BFE.dev】

本文探讨了BEF.dev中如何使用管道操作(pipe())结合函数组合(如functioncurrying)和Array的API(reduce)来处理数组参数的函数调用。作者提供了两种解决方案,一种是使用for循环,另一种是利用reduce方法简化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值