Pipes

A pipe is a function or operator that allows us to pass the output of a function as the input of another. JavaScript and TypeScript don't support piles natively (as an operator), but we can implement our pipes using the following function:

const pipe = <T>(...fns: Array<(arg: T) => T>) =>
    (value: T) => fns.reduce((acc, fn) => fn(acc), value); 

We are going to use the curry3, trim, capitalize, and replace functions that we declared previously in this chapter:

const trim = (s: string) => s.trim(); 
const capitalize = (s: string) => s.toUpperCase(); 
 
const replace = curry3( 
    (s: string, f: string, r: string) => s.split(f).join(r) 
); 

We can then use the pipe function to declare a new function:

const trimCapitalizeAndReplace = pipe( trim, ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.