Last active
July 2, 2019 01:57
-
-
Save leunardo/4084d91cc880f70381e11e745a1952be to your computer and use it in GitHub Desktop.
JS Pipe (rxjs-like)
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
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