DEV Community

cem kaan kosali
cem kaan kosali

Posted on

3

Functional Typescript Series

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();
Enter fullscreen mode Exit fullscreen mode
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);
view raw composeMany.ts hosted with ❤ by GitHub

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →