Skip to content

Instantly share code, notes, and snippets.

@anhdiepmmk
Last active September 28, 2021 04:24
Show Gist options
  • Save anhdiepmmk/a84e340ee7eb244a1da6a5c193bed182 to your computer and use it in GitHub Desktop.
Save anhdiepmmk/a84e340ee7eb244a1da6a5c193bed182 to your computer and use it in GitHub Desktop.
A quick introduction to pipe() and compose() in JavaScript
// 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' });
// 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)
})();
// 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