UNPKG

@konkon5991/pipeline-ts

Version:

A lightweight TypeScript library for Railway Oriented Programming (ROP) with comprehensive functional programming utilities.

55 lines 1.89 kB
import { isFailure } from "./result"; /** * The `pipeSync` function composes multiple synchronous functions. * @template T - The tuple of functions. * @template ExtractError<T> - The error type extracted from the tuple of functions. * @param {...SyncPipeline<T, ExtractError<T>>} fns - The functions to compose. * @returns {Function} A function that takes the input of the first function and returns a `Result` of the last function's output type and the error type. * * @example * const pipeline = pipeSync( * (input: string) => success(parseInt(input)), * (num: number) => success(num + 1), * (num: number) => success(num.toString()) * ); * * const result = pipeline("42"); * fold( * (err) => console.log("Error:", err), * (val) => console.log("Success:", val) * )(result); */ export const pipeSync = (...fns) => { return (arg) => { let result = fns[0](arg); for (const fn of fns.slice(1)) { if (isFailure(result)) break; result = fn(result.value); } return result; }; }; /** * Creates a lazy pipeline that only executes when called. * @template T - The tuple of functions. * @template ExtractError<T> - The error type extracted from the tuple of functions. * @param {...SyncPipeline<T, ExtractError<T>>} fns - The functions to compose. * @returns {Object} An object with `run` method to execute the pipeline. */ export const lazyPipe = (...fns) => { return { run: (arg) => { let result = fns[0](arg); for (let i = 1; i < fns.length; i++) { if (isFailure(result)) break; result = fns[i](result.value); } return result; }, map: (fn) => lazyPipe(...fns, fn), flatMap: (fn) => lazyPipe(...fns, fn) }; }; //# sourceMappingURL=pipe-sync.js.map