javascript is about to get a pipeline operator (Goddess willing). here's why that's such a great thing, especially when combined with partial application & higher-order functions.
first off, let's talk about what the pipeline operator actually is, and why you should be so excited by it.
const lower = str => str.toLowerCase()
const stripWhiteSpace = str => str.replace(/[\s]+/g, '_')
const normalizedString = stripWhiteSpace(lower(' HELLO, worLD'))
// 'hello, world'
// avoid nesting function application with pipeline!
const normalizedString = ' HELLO, worLD'
|> lower
|> stripWhiteSpace
// 'hello, world'
the pipeline operator is simply saying "take the result of this function, and pass it as a parameter to the next." it creates a pipeline in the most intuitive sense of the word. if you're doing a long series of transformations, the pipeline operator will be invaluable.
HOWEVER! a very very VERY big win comes when we have standalone, curried map
and filter
functions! the word "curried" simply means that you can pass the parameters your function needs separately; rather than having to assign values to intermediate variables, you can pass parameters one at a time. if you pass fewer than the needed parameters, the curried function will return you a new function that you can call with the other params. here's an example: of what i mean:
const users = [
{ name: 'Angela', score: 100, dq: false },
{ name: 'Brent', score: 79, dq: true },
{ name: 'Charlie', score: 30, dq: false },
{ name: 'Daniela', score: 87, dq: false },
{ name: 'Emily', score: 56, dq: true },
{ name: 'Frank', score: 34, dq: false },
{ name: 'Guillaume', score: 78, dq: false }
]
const takeThree = arr => arr.slice(0, 2)
const not = i => !i
const leaderboard = users
|> filter(user => not(user.dq))
|> sort((a, b) => a.score < b.score)
|> map(user => user.name)
|> takeThree
in this way, we're transforming our entire list of users and their respective scores into a three-length leaderboard, organized by (but not displaying) score, and respecting disqualifications (for whatever reason we might have disqualifications).
the pipeline operator will be super cool by itself, but it can become especially powerful in the context of curried/partially applied functions in javascript.
thanks for reading!