Skip to content

实现一个pipe函数

题目链接

https://bigfrontend.dev/problem/what-is-composition-create-a-pipe

题目说明

有下面几个运算函数

js
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函数,输入数组,返回函数,该函数接收一个参数,调用返回执行结果。

js
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

题目解析

  • pipe函数的参数是数组,使用reduce正好
  • 返回一个函数,参数是reduce的初始值
js
/**
 * @param {Array<(arg: any) => any>} funcs
 * @return {(arg: any) => any}
 */
function pipe(funcs) {
	return (arg) => funcs.reduce((prev, val) => val(prev), arg)
}

MIT Licensed