Skip to content

Instantly share code, notes, and snippets.

@leunardo
Last active July 2, 2019 01:57
Show Gist options
  • Save leunardo/4084d91cc880f70381e11e745a1952be to your computer and use it in GitHub Desktop.
Save leunardo/4084d91cc880f70381e11e745a1952be to your computer and use it in GitHub Desktop.
JS Pipe (rxjs-like)
function removeFalsyValues(values) {
return values.filter(value => Boolean(value));
}
function showValues(values) {
values.forEach(value => console.log(`Got value: ${value}`));
}
function greaterThanZero(values) {
return values.filter(value => value > 0);
}
const values = [1, 0, undefined, 43];
/* Without pipe: need to read from right to left */
showValues(greaterThanZero(removeFalsyValues(values)));
/* With pipe: */
pipe(
removeFalsyValues,
greaterThanZero,
showValues
)(values);
function pipe(fns) {
return (arg) => fns.reduce((prev, fn) => fn(prev), arg);
}
/* extra function with fluent language */
function pipeValue(args) {
return {
to: (...fns) => pipe(...fns)(args)
};
}
pipeValue(value).to(
removeFalsyValues,
greaterThanZero,
showValues
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment