Skip to content

Instantly share code, notes, and snippets.

@koyanloshe
Last active August 10, 2022 19:19
Show Gist options
  • Save koyanloshe/47a68e590cd49b4e06bab1e30097a6d1 to your computer and use it in GitHub Desktop.
Save koyanloshe/47a68e590cd49b4e06bab1e30097a6d1 to your computer and use it in GitHub Desktop.
Pipe & Compose in Javascript #Javascript #fp
const compose = (...fns) => {
return (x) => {
return fns.reduceRight((v,f) => {
return f(v)
}, x)
}
}
// From Kyle Simpson's works
// The nextCurried function is an immediately invoked function
// The curry function can accept a function and the number of times it is to run as parameters.
function curry(fn, arity= fn.length){
return (function nextCurried(prevArgs){
return function curried(nextArg){
var args = [...prevArgs, nextArg];
if(args.length >= arity){
return fn(...args);
}else{
return nextCurried(args);
}
}
})([]);
}
//so earlier if the notCurried function accepted 3 params like below,
const notCurried = function(a,b,c){}
//execute the curried function by calling below
const curried = curry(notCurried)(a)(b)
const testfunction = (x, y) => x + y;
// If y is constant 10
const partialTestFunction10 = testFunction.bind(null, 10);
const pipe = (...fns) => {
return (x) => {
return fns.reduce((v,f) => {
return f(v)
}, x)
}
}
// Async compose
const compose = (…functions) => input => functions.reduceRight((chain, func) => chain.then(func), Promise.resolve(input));
// Functions fn1, fn2, fn3 can be standard synchronous functions or return a Promise
compose(fn3, fn2, fn1)(input).then(result => console.log(`Do with the ${result} as you please`))
const pipe = (…functions) => input => functions.reduce((chain, func) => chain.then(func), Promise.resolve(input));
// Functions fn1, fn2, fn3 can be standard synchronous functions or return a Promise
pipe(fn1, fn2, fn3)(input).then(result => console.log(`Do with the ${result} as you please`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment