Today I Learned - Rocky Kev

TIL the simulating a Pipe function

POSTED ON:

TAGS:

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.

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!

There’s currently a perpetual TC39 proposal for adding a true Pipe operator (|>) to JavaScript here: https://github.com/tc39/proposal-pipeline-operator


Related TILs

Tagged:

TIL why you should always use textContent

Today I learned the difference between 'Node.textContent'. It handles all elements, even hidden ones. It also prevents XSS attacks since it strips tags.

TIL prepend

When you're creating new elements in Javascript, you want to attach the new element to something that exists in the DOM already. You do that with append, and prepend.

TIL the simulating a Pipe function

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.