Skip to content

Instantly share code, notes, and snippets.

@JamesJansson
Created January 20, 2023 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesJansson/923f60d0738a9cae1622947da66d4a0b to your computer and use it in GitHub Desktop.
Save JamesJansson/923f60d0738a9cae1622947da66d4a0b to your computer and use it in GitHub Desktop.
The pipe functions you want in JS right now
// 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