Last active
September 28, 2021 04:24
-
-
Save anhdiepmmk/a84e340ee7eb244a1da6a5c193bed182 to your computer and use it in GitHub Desktop.
A quick introduction to pipe() and compose() in JavaScript
This file contains hidden or 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
// What about compose()? | |
// It’s just pipe in the other direction. | |
compose = (...function) => (value) => fns.reduceRight((currentValue, currentFunction) => currentFunction(currentValue), value); | |
compose( | |
reverse, | |
get6Characters, | |
uppercase, | |
getName | |
)({ name: 'anhdiepmmk' }); |
This file contains hidden or 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
// https://www.30secondsofcode.org/js/s/pipe-async-functions | |
const pipeAsyncFunctions = (...fns) => | |
arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); | |
const sum = pipeAsyncFunctions( | |
x => x + 1, | |
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), | |
x => x + 3, | |
async x => (await x) + 4 | |
); | |
(async() => { | |
console.log(await sum(5)); // 15 (after one second) | |
})(); |
This file contains hidden or 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
// original tutorial url: https://www.freecodecamp.org/news/pipe-and-compose-in-javascript-5b04004ac937/ | |
pipe = (...functions) => (value) => { | |
return functions.reduce((currentValue, currentFunction) => { | |
return currentFunction(currentValue); | |
}, value); | |
}; | |
getName = (person) => person.name; | |
uppercase = (string) => string.toUpperCase(); | |
get6Characters = (string) => string.substring(0, 6); | |
const avalue = pipe( | |
getName, | |
uppercase, | |
get6Characters | |
)({name: 'anhdiepmmk'}); | |
console.log(avalue); | |
// OUTPUT: ANHDIE | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment