DEV Community

Discussion on: Declarative functions

Collapse
 
richytong profile image
Richard Tong

Try out pipe and tap. pipe takes an array of functions and lets you chain them together so that the return value of one function becomes the first argument to the next. tap takes a function and some input, calls the function with input, and returns the original input (good for effects). Both of these functions used together can get you started composing functions pretty fast. Here are some implementations for the functions.

const functionConcat = (funcA, funcB) => value => funcB(funcA(value))

// pipe(funcs Array<function>)(value any) -> any
const pipe = funcs => funcs.reduce(functionConcat)

const tap = func => value => {
  func(value)
  return value
}
Enter fullscreen mode Exit fullscreen mode

Example with pipe, tap, map, and filter

pipe([
  filter(number => number % 2 == 1), // isOdd
  map(number => number ** 2), // square
  tap(console.log),
])([1, 2, 3, 4, 5]) // -> [1, 9, 25]
Enter fullscreen mode Exit fullscreen mode

I created a library with async-capable versions of the above and more. Check it out at rubico.land