Created
June 4, 2020 12:59
-
-
Save zaetrik/01cc953f580d2d62088033226912f93a to your computer and use it in GitHub Desktop.
Compose Functions
This file contains 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
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