Skip to content

Instantly share code, notes, and snippets.

@juliencrn
Created April 11, 2021 00:12
Show Gist options
  • Save juliencrn/a9d9e6c3f6c3033a4e8add77a853f0e5 to your computer and use it in GitHub Desktop.
Save juliencrn/a9d9e6c3f6c3033a4e8add77a853f0e5 to your computer and use it in GitHub Desktop.
// Pipe in JS
// @see
// - https://www.freecodecamp.org/news/pipe-and-compose-in-javascript-5b04004ac937/
// - https://medium.com/javascript-scene/reduce-composing-software-fe22f0c39a1d
// Utility functions for example
const getName = (person) => person.name
const uppercase = (string) => string.toUpperCase()
const get6Characters = (string) => string.substring(0, 6)
const reverse = (string) =>
string
.split('')
.reverse()
.join('')
// Units logs
const person = { name: 'Buckethead' }
console.log({
person,
getName: getName(person), // 'Buckethead'
uppercase: uppercase(person.name), // 'BUCKETHEAD'
get6Characters: get6Characters(person.name), // 'Bucket'
reverse: reverse(person.name), // 'daehtekcuB'
})
// Traditional way
const traditional = reverse(get6Characters(uppercase(getName({ name: 'Buckethead' }))));
console.log({ traditional }) // 'TEKCUB'
// Pipe
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)
const outputWithPipe = pipe(
getName,
uppercase,
get6Characters,
reverse
)({ name: 'Buckethead' });
console.log('Result with pipe()', {
traditional, // 'TEKCUB'
outputWithPipe, // 'TEKCUB'
isEqual: traditional === outputWithPipe // true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment