export class ZQueue { functions = [] autoRun = false running = false context = {} constructor (config = {}) { return this.options(config) } options (config = {}) { if (typeof config.autoRun !== 'undefined') this.autoRun = !!config.autoRun if (typeof config.context !== 'undefined') this.context = config.context return this } push (fn) { if (typeof fn !== 'function') throw new Error('Cannot add non-functions to the queue') this.functions.push(fn) if (this.autoRun) this.executeEach() return this } async executeAll (context) { if (this.running) return this.options({ context }) this.running = true const results = [] let i = -1 while (++i < this.functions.length) { if (typeof this.functions[i] === 'function') results.push(Promise.resolve(this.functions[i].call(context))) } const all = await Promise.all(results) this.running = false return all } async executeEach (context) { if (this.running) return this.options({ context }) this.running = true const results = [] for (const fn of this.functions) { if (typeof fn === 'function') { results.push(await Promise.resolve(fn.call(context))) } } this.running = false return results } }