Emulate JavaScript’s proposed pipeline operator with a helper function

JavaScript’s proposed pipeline operator has been stuck at stage 1 for a long time, and I’m skeptical it’ll ever be added to the language.

It’s easy to emulate with a helper function. You have to type a few extra characters, but once the code’s written, it’s very readable and gets the job done.

Playground link

interface Pipeline<T> {
    <R>(cb: (v: T) => R): Pipeline<R>;
    value: T;
}
function pipe(): Pipeline<undefined>;
function pipe<T>(value: T): Pipeline<T>;
function pipe(value?: any): any {
    function chain(cb: any) {
        return pipe(cb(value));
    }
    chain.value = value;
    return chain as any;
}

function add(a: number, b: number) {
    return a + b;
}
declare function subtract(a: number, b: number) {
    return a - b;
}

const r = pipe()
    (_ => add(2, 3))
    (v => subtract(v, 2))
    .value;

Updated:

Leave a Comment