11. 实现一个pipe函数

frontend

# 题目链接

https://bigfrontend.dev/problem/what-is-composition-create-a-pipe (opens new window)

# 题目说明

有下面几个运算函数

const times = (y) =>  (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) =>  (x) => x - y
const divide = (y) => (x) => x / y
1
2
3
4

实现一个pipe函数,输入数组,返回函数,该函数接收一个参数,调用返回执行结果。

pipe([
  times(2),
  times(3)
])  
// x * 2 * 3

pipe([
  times(2),
  plus(3),
  times(4)
]) 
// (x * 2 + 3) * 4

pipe([
  times(2),
  subtract(3),
  divide(4)
]) 
// (x * 2 - 3) / 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 题目解析

  • pipe函数的参数是数组,使用reduce正好
  • 返回一个函数,参数是reduce的初始值
/**
 * @param {Array<(arg: any) => any>} funcs 
 * @return {(arg: any) => any}
 */
function pipe(funcs) {
	return (arg) => funcs.reduce((prev, val) => val(prev), arg)
}
1
2
3
4
5
6
7
更新时间: 2022-11-21 16:22