Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created June 4, 2020 12:59
Show Gist options
  • Save zaetrik/01cc953f580d2d62088033226912f93a to your computer and use it in GitHub Desktop.
Save zaetrik/01cc953f580d2d62088033226912f93a to your computer and use it in GitHub Desktop.
Compose Functions
const composeLeftToRight = <F extends (x: any) => any>(...fns: Array<F>) => (
...[x]: Parameters<F>
): ReturnType<F> => fns.reduce((y, f) => f(y), x);
const composeRightToLeft = <F extends (x: any) => any>(...fns: Array<F>) => (
...[x]: Parameters<F>
): ReturnType<F> => fns.reduceRight((y, f) => f(y), x);
const addTwo = (x: number) => x + 2;
const double = ( x: number) => x * 2;
const doubleThenAdd = composeRightToLeft(addTwo, double);
console.log(doubleThenAdd(4)); // 10
const addThenDouble = composeLeftToRight(addTwo, double);
console.log(addThenDouble(4)); // 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment