Open1

TypeScriptでPipeをクラスで実装

Nakano as a ServiceNakano as a Service
class Pipe<T> {
  private funcs: ((x: T) => any)[] = [];

  constructor(private value: T) {}

  pipe<U>(f: (x: T) => U): Pipe<U> {
    this.funcs.push(f);
    return this as unknown as Pipe<U>;
  }

  build(): T {
    return this.funcs.reduce((acc, f) => f(acc) as any, this.value);
  }
}

const x = new Pipe(1)
  .pipe((x) => x + 1)
  .pipe((x) => x * 2)
  .pipe((x) => x.toString())
  .pipe((x) => `${x}!`)
  .build();