@ipp/cli
Version:
An image build orchestrator for the modern web
61 lines (60 loc) • 2.08 kB
JavaScript
;
/**
* Image Processing Pipeline - Copyright (c) Marcus Cemes
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapParallel = void 0;
const denque_1 = __importDefault(require("denque"));
const events_1 = require("events");
const object_stream_1 = require("../object_stream");
function mapParallel(concurrency, fn, complete) {
return (source) => (0, object_stream_1.createObjectStream)((async function* () {
let active = 0;
let ended = false;
const events = new events_1.EventEmitter();
const output = new denque_1.default();
const slot = async () => {
while (active === concurrency) {
await (0, events_1.once)(events, "complete");
}
++active;
};
(async () => {
for await (const item of source) {
await slot();
(async () => {
const result = await fn(item);
if (result === null)
return;
if (Array.isArray(result)) {
result.forEach((x) => output.push(x));
}
else {
output.push(result);
}
--active;
events.emit("complete");
})();
}
ended = true;
events.emit("complete");
})();
while (active !== 0 || !ended) {
if (output.isEmpty()) {
await (0, events_1.once)(events, "complete");
}
while (!output.isEmpty()) {
yield output.shift();
}
}
if (complete)
await complete();
})());
}
exports.mapParallel = mapParallel;