flowed
Version:
A fast and reliable flow engine for orchestration and more uses in *Node.js*, *Deno* and the browser
70 lines • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueQueueManager = void 0;
class ValueQueueManager {
static fromSerializable(serializable) {
const queueNames = Object.keys(serializable);
const instance = new ValueQueueManager(queueNames);
instance.queues = serializable;
instance.nonEmptyQueues = queueNames.reduce((acc, name) => {
if (instance.queues[name].length > 0) {
acc.add(name);
}
return acc;
}, new Set());
return instance;
}
constructor(queueNames) {
this.nonEmptyQueues = new Set();
this.queueNames = [...queueNames];
this.queues = queueNames.reduce((acc, name) => {
acc[name] = [];
return acc;
}, {});
}
push(queueName, value) {
if (!this.queueNames.includes(queueName)) {
throw new Error(`Queue name ${queueName} does not exist in queue manager. Existing queues are: [${this.queueNames.join(', ')}].`);
}
this.nonEmptyQueues.add(queueName);
this.queues[queueName].push(value);
}
getEmptyQueueNames() {
return this.queueNames.reduce((acc, name) => {
if (this.queues[name].length === 0) {
acc.push(name);
}
return acc;
}, []);
}
popAll() {
this.validateAllNonEmpty();
return this.queueNames.reduce((acc, name) => {
acc[name] = this.queues[name].shift();
if (this.queues[name].length === 0) {
this.nonEmptyQueues.delete(name);
}
return acc;
}, {});
}
topAll() {
this.validateAllNonEmpty();
return this.queueNames.reduce((acc, name) => {
acc[name] = this.queues[name][0];
return acc;
}, {});
}
toSerializable() {
return JSON.parse(JSON.stringify(this.queues));
}
validateAllNonEmpty() {
if (!this.allHaveContent()) {
throw new Error(`Some of the queues are empty: [${this.getEmptyQueueNames().join(', ')}].`);
}
}
allHaveContent() {
return this.nonEmptyQueues.size === this.queueNames.length;
}
}
exports.ValueQueueManager = ValueQueueManager;
//# sourceMappingURL=value-queue-manager.js.map