A pipe function builder with tiny size and type-safe.
npm install @deviltea/tiny-pipe
import { createPipe } from '@deviltea/tiny-pipe'
const square = (x: number) => x * x
const minusOne = (x: number) => x - 1
// You may create a new executable function
// typeof squareAndMinusOne === (x: number) => number
const squareAndMinusOne = createPipe()
.pipe(square)
.pipe(minusOne)
.execute
// Or directly execute the function
createPipe()
.pipe(square)
.pipe(minusOne)
.execute(3) // 8
// The pipe function is type-safe
createPipe()
.pipe(square)
.pipe(minusOne)
.execute('3') // Argument type error!
createPipe()
.pipe(square)
.pipe((v: string) => v) // Handler's parameter type error!
.pipe(minusOne)
.execute(3)
// During the execution, each handler of pipe
// will wait for the previous handler to finish,
// so you can pipe any async or sync functions together freely.
const myFn = createPipe()
.pipe((x /* : number */) => Promise.resolve(x + 1))
.pipe(async (x /* : number */) => x * 2)
.pipe((x /* : number */) => x - 1)
.execute
function getNumberOrThrow() {
const n = Math.random()
if (n < 0.5)
throw new Error('Oops!')
return n
}
const myFn = createPipe()
.pipeSafe(getNumberOrThrow) // If the handler may throw an error, you can use `pipeSafe` to wrap it.
.pipe((safeData) => { // It will wrap the result or error into an object. Do not destruct it to let type narrowing work.
if (safeData.status === 'resolved') // type narrowing
console.log(safeData.result /* :number */)
else if (safeData.status === 'rejected') // type narrowing
console.log(safeData.reason /* :Error */)
})
.execute