simple-in-memory-queue
Version:
A simple in-memory queue, for nodejs and the browser, with consumers for common usecases.
47 lines • 1.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createQueue = void 0;
const event_stream_pubsub_1 = require("event-stream-pubsub");
const split_1 = require("./split");
const castOptionalStartEndToSlice = (start, end) => end !== undefined && start !== undefined
? { start, end }
: start
? { start: 0, end: start }
: { start: 0, end: 1 };
const createQueue = ({ order }) => {
// instantiate the in memory data store
let data = [];
// instantiate the event streams
const on = {
push: new event_stream_pubsub_1.EventStream(),
peek: new event_stream_pubsub_1.EventStream(),
pop: new event_stream_pubsub_1.EventStream(),
};
// define the methods for interacting with the data store
return {
push: (item) => {
const items = Array.isArray(item) ? item : [item];
data.push(...items);
on.push.publish({ items });
},
peek: (start, end) => {
const slice = castOptionalStartEndToSlice(start, end);
const { selection } = (0, split_1.split)({ data, order, slice });
on.peek.publish({ items: selection });
return selection;
},
pop: (start, end) => {
const slice = castOptionalStartEndToSlice(start, end);
const { selection, remainder } = (0, split_1.split)({ data, order, slice });
on.pop.publish({ items: selection });
data = remainder; // update the data to remove the selection
return selection;
},
get length() {
return data.length;
},
on,
};
};
exports.createQueue = createQueue;
//# sourceMappingURL=createQueue.js.map