UNPKG

@gecut/utilities

Version:

The ultimate utility toolkit from Gecut Company, crafted with TypeScript for optimal speed and efficiency. Designed to boost productivity with a suite of fast and optimized tools.

110 lines 3.34 kB
import { uid } from './uid.js'; import { untilIdle, untilMS, untilNextFrame } from './wait/wait.js'; /** * GecutQueue class */ export class GecutQueue { /** * Creates a new GecutQueue instance * @param {string} name - The name of the queue * @param {('animationFrame' | 'idleCallback' | number)} delayPeriod - The delay period for the queue */ constructor(name, delayPeriod) { /** * The queue map * @type {Map<string, Promise<unknown>>} */ this.queue = new Map(); /** * The values map * @type {Map<string, unknown>} */ this.values = new Map(); /** * The name of the queue * @type {string} */ this.name = name; /** * The delay period function * @type {() => Promise<unknown>} */ this.delayPeriod = this.getDelayPeriodFunction(delayPeriod); } /** * Pushes a new promise to the queue * @param {Promise<unknown>} promise - The promise to push * @param {string} [id] - The optional id for the promise * @returns {{ id: string }} - The id of the pushed promise */ push(promise, id) { id ??= uid(); this.queue.set(id, this.waitForAllFinish() .then(() => this.delayPeriod()) .then(() => { this.runningId = id; return promise; }) .then((value) => { this.runningId = undefined; this.queue.delete(id); this.values.set(id, value); return value; })); return { id }; } /** * Gets the value of a promise * @param {string} id - The id of the promise * @returns {Promise<unknown>} - The promise value */ getValue(id) { if (this.values.has(id)) { return this.values.get(id); } return (this.queue.get(id) ?? Promise.resolve(undefined)); } /** * Checks if a promise is running * @param {string} id - The id of the promise * @returns {boolean} - Whether the promise is running */ isRunning(id) { return this.runningId === id; } isFinished(id) { return this.values.has(id); } /** * Waits for a promise to finish * @param {string} id - The id of the promise * @returns {Promise<unknown>} - The promise result */ waitForFinish(id) { return this.queue.get(id) ?? Promise.resolve(); } /** * Waits for all promises to finish * @returns {Promise<unknown[]>} - The promise results */ waitForAllFinish() { return Promise.all(this.queue.values()); } /** * Gets the delay period function based on the delay period type * @private * @param {('animationFrame' | 'idleCallback' | number)} delayPeriod - The delay period type * @returns {() => Promise<unknown>} - The delay period function */ getDelayPeriodFunction(delayPeriod) { switch (delayPeriod) { case 'animationFrame': return untilNextFrame.bind(null); case 'idleCallback': return untilIdle.bind(null); default: return untilMS.bind(null, delayPeriod); } } } //# sourceMappingURL=queue.js.map