Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Last active December 16, 2020 06:34
Show Gist options
  • Save renaudtertrais/fbb1a78d495bd72b8b318fb7368644e2 to your computer and use it in GitHub Desktop.
Save renaudtertrais/fbb1a78d495bd72b8b318fb7368644e2 to your computer and use it in GitHub Desktop.
Simple ES6 compose & pipe function
const compose = (...fns) => (...args) => {
return fns.slice(0, -1).reduceRight((res, fn) => fn(res),
fns[fns.length -1].apply(null,args)
);
};
const pipe = (f1, ...fns) => (...args) => {
return fns.reduce((res, fn) => fn(res), f1.apply(null,args));
};
// example
const add2 = (n) => n + 2;
const times2 = (n) => n * 2;
const times2add2 = compose(add2, times2);
const add2tiems2 = pipe(add2, times2);
const add6 = compose(add2, add2, add2);
times2add2(2); // 6
add2tiems2(2); // 8
add6(2); // 8
@renaudtertrais
Copy link
Author

@Miteshdv
Copy link

Miteshdv commented Jun 3, 2017

Thanks nice work

@doasync
Copy link

doasync commented Sep 15, 2017

You can replace f1.apply(null,args) with f1(...args)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment