smokinjoe / advent-of-code-2023

Created with CodeSandbox
https://codesandbox.io/p/github/smokinjoe/advent-of-code-2023
0 stars 0 forks source link

Add new pipe function #16

Open smokinjoe opened 9 months ago

smokinjoe commented 9 months ago

What does this function do?

const surprise = (...fns) => input => fns.reduce(
  (acc, fn) => fn(acc), input
)

It’s a pipe function that allows you to chain multiple operations together by taking a series of functions as arguments and applying them in a specific order to the input.

Wow, words.

Instead of doing something like this.

const toUpperCase = str => str.toUpperCase()
const removeSpaces = str => str.replace(/\s/g, "")
const addExclamation = str => str + "!"

toUpperCase(removeSpaces(addExclamation("Subscribe to Bytes")))

You can do something like this.

const pipe = (...fns) => input => fns.reduce(
  (acc, fn) => fn(acc), input
)

const formatString = pipe(toUpperCase, removeSpaces, addExclamation)

formatString("Subscribe to Bytes") // SUBSCRIBETOBYTES!