Created
December 12, 2021 17:37
-
-
Save codenamezjames/449930a7c9c6e532ca029bb0103373b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment