Skip to content

Micro alternative using streams #15

@sukima

Description

@sukima

This is not as robust as yours but thought the implementation of using WebStreams was interesting enough to share:

function pipe() {
  const pipeline = new Set();
  const builder = (fn) => {
    const unit = {
      toStream: () => new TransformStream({
        transform: async (data, cont) => cont.enqueue(await fn(data)),
      }),
      [Symbol.toPrimitive]: () => (pipeline.add(unit), 0),
    };
    return unit;
  };
  builder.run = (items) => {
    let stream = new ReadableStream({
      start: (controller) => {
        for (const item of items) controller.enqueue(item);
        controller.close();
      },
    })
    pipeline.forEach((unit) => stream = stream.pipeThrough(unit.toStream()));
    return Array.fromAsync(stream);
  };
  return builder;
}

{
  const $ = pipe();
  $(x => x + 1)
    | $(x => x + 1)
    | $(x => x + 1)
    | $(x => x + 1)
    | $(x => x + 1);
  console.log(await $.run([0, 10, 20, 30, 50]));
  console.log(await $.run([100, 110, 120, 130, 150]));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions