yarn add pipe-ts
npm install pipe-ts
Create a new function which pipes its value through the list functions.
const add1 = (n: number) => n + 1;
const times2 = (n: number) => n * 2;
const add1ThenTimes2 = pipe(
add1,
times2,
);
const result: number = add1ThenTimes2(1);
assert.strictEqual(result, 4);
Allows first function to have any number of parameters (0+), thanks to TypeScript's generic rest parameters
// First function has multiple parameters
const difference = (a: number, b: number) => a - b;
const add1 = (n: number) => n + 1;
const differenceThenAdd1 = pipe(
difference,
add1,
);
const result: number = differenceThenAdd1(5, 4);
assert.strictEqual(result, 2);
// First function has 0 parameters
const getNumber = () => 1;
const add1 = (n: number) => n + 1;
const getNumberThenAdd1 = pipe(
getNumber,
add1,
);
const result: number = getNumberThenAdd1();
assert.strictEqual(result, 2);
Transform a value by piping it through the listed functions. Sugar syntax for pipe(f, g)(value)
.
const add1 = (n: number) => n + 1;
const times2 = (n: number) => n * 2;
const result: number = pipeWith(1, add1, times2);
assert.strictEqual(result, 4);
pipe
and pipeWith
currently support up to 9 functions. If need be, we are open to adding more overloads to increase this limit.
We are also open to adding an array overload, so any number of funtions can be passed.
If a function passed to pipe
or pipeWith
relies on a specific context of execution (this
), you cannot call it by passing the reference (point-free style).
Use an anonymous function instead.
Bad
pipeWith('foo', localStorage.getItem);
Good
pipeWith('foo', key => localStorage.getItem(key));
Also good
pipeWith('foo', localStorage.getItem.bind(localStorage)),
yarn
npm run start