UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

52 lines (46 loc) 1.34 kB
'use strict'; var stream = require('stream'); // src/invariant.ts var prefix = "Invariant failed"; function invariant(condition, message) { if (condition) { return; } if (typeof message === "string" || typeof message === "function") { const provided = typeof message === "function" ? message() : message; const value = provided ? `${prefix}: ${provided}` : prefix; throw new Error(value); } if (message) throw message; throw new Error(prefix); } // src/isArray.ts function isArray(val) { return val && Array.isArray(val); } // src/mergeStreams.ts function mergeStreams(streams) { invariant(isArray(streams), "Expect input an array streams"); const passThroughStream = new stream.PassThrough({ objectMode: true }); if (streams.length === 0) { passThroughStream.end(); return passThroughStream; } let streamsCount = streams.length; for (const stream of streams) { invariant(!(typeof stream?.pipe === "function"), "Expect a stream, got "); stream.pipe(passThroughStream, { end: false }); stream.on("end", () => { streamsCount--; if (streamsCount === 0) { passThroughStream.end(); } }); stream.on("error", (error) => { passThroughStream.emit("error", error); }); } return passThroughStream; } exports.mergeStreams = mergeStreams;