Function composition is the process of combining two or more functions to produce a new function. Composing functions together is like snapping together a series of pipes for our data to flow through.
const trim = (s: string) => s.trim();
const capitalize = (s: string) => s.toUpperCase();
const compose = <T>(f: (x: T) => T, g: (x: T) => T) => (x: T) => f(g(x)); | |
const compose2 = <T1, T2, T3>(f: (x: T2) => T3, g: (x: T1) => T2) => (x: T1) => f(g(x)); | |
const composeMany = <T>(...functions: Array<(arg: T) => T>) => | |
(arg: any) => | |
functions.reduce((prev, curr) => { | |
return curr(prev); | |
}, arg); | |
const func1 = <T>(x: T) => x; | |
const func2 = <T>(x: T) => x; | |
const func3 = <T>(x: T) => x; | |
const func4 = <T>(x: T) => x; | |
const func5 = <T>(x: T) => x; | |
const composed1 = composeMany(func1, func2, func3, func4); | |
const composed2 = composeMany(func1, func2, func3, func4, func5); |
Top comments (0)