Created
January 20, 2023 13:06
-
-
Save JamesJansson/923f60d0738a9cae1622947da66d4a0b to your computer and use it in GitHub Desktop.
The pipe functions you want in JS right now
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// There's a proposal for a new 'pipe' operation |> https://github.com/tc39/proposal-pipeline-operator | |
// Below are two methods (`pipe` and `pwhyp`) you could use right now to achieve the same result. | |
// `pipe` easy version. Use `.next(someFunction)` to apply a new function | |
function pipe(value) { | |
return { | |
next: (f) => pipe(f(value)), | |
end: () => value, | |
}; | |
} | |
// inline | |
const val1 = pipe(3).next(x=>x+2).next(x=>x*x).end(); | |
// multiline | |
const val2 = pipe(3) | |
.next((x) => x + 2) | |
.next((x) => x * x) | |
.end(); | |
// using functions | |
const val3 = pipe(3) | |
.next(add2) | |
.next(square) | |
.end(); | |
// `pwhyp` = pipe + 'why???'. Hardcore mode for people who like counting brackets | |
function pwhyp(value) { | |
return (f) => { | |
if (typeof f === 'function') return pipe(f(value)); | |
else if (typeof f === 'undefined') return value; | |
else throw new Error('input not a function'); | |
}; | |
} | |
// inline | |
const val4 = pwhyp(3)((x) => x + 2)((x) => x * x)(); | |
// multiline (note: // is so that eslint formats correctly) | |
const val5 = pwhyp(3)( | |
(x) => x + 2 // | |
)( | |
(x) => x * x // | |
)(); | |
// using functions | |
const val6 = pwhyp(3)(add2)(square)(); | |
// Functions used above | |
function add2(x){ | |
return x + 2; | |
} | |
function square(x){ | |
return x * x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment