Created
July 19, 2023 17:46
-
-
Save fernandocamargo/7cc72d867f9355cdba6dabbc086d0bbf 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
const delay = () => (Math.floor(Math.random() * 6) + 1) * 1000; | |
const callback1 = () => | |
new Promise((resolve) => | |
setTimeout(() => resolve(console.log({ callback: 1 })), delay()) | |
); | |
const callback2 = () => | |
new Promise((resolve) => | |
setTimeout(() => resolve(console.log({ callback: 2 })), delay()) | |
); | |
const callback3 = () => | |
new Promise((resolve) => | |
setTimeout(() => resolve(console.log({ callback: 3 })), delay()) | |
); | |
const callback4 = () => | |
new Promise((resolve) => | |
setTimeout(() => resolve(console.log({ callback: 4 })), delay()) | |
); | |
class QueueProcessingCallback { | |
static MAX_CONCURRENTLY_EXECUTING = 5; | |
static FIFO = "FIFO"; | |
static LIFO = "LIFO"; | |
constructor(type = this.constructor.FIFO) { | |
this.poll = 0; | |
this.queue = []; | |
this.type = type; | |
return this; | |
} | |
debug = () => { | |
const { poll, queue, type } = this; | |
return console.log({ poll, queue, type }); | |
}; | |
flush = () => { | |
const { | |
constructor: { FIFO, LIFO }, | |
poll, | |
process, | |
queue, | |
type, | |
} = this; | |
const { [type]: index } = { [FIFO]: 0, [LIFO]: -1 }; | |
const [promise] = queue.splice(index, 1); | |
this.poll = poll - 1; | |
this.queue = queue; | |
return promise ? process(promise) : this; | |
}; | |
process = (promise) => { | |
const { | |
constructor: { MAX_CONCURRENTLY_EXECUTING: limit }, | |
flush, | |
poll, | |
queue, | |
} = this; | |
const full = poll >= limit - 1; | |
this.poll = poll + (full ? 0 : 1); | |
this.queue = queue.concat(full ? promise : []); | |
return full ? this : promise().then(flush); | |
}; | |
} | |
const fifo = new QueueProcessingCallback(); | |
fifo.process(callback1); | |
fifo.process(callback2); | |
fifo.process(callback3); | |
fifo.process(callback4); | |
fifo.process(callback1); | |
fifo.process(callback2); | |
fifo.process(callback3); | |
fifo.process(callback4); | |
const lifo = new QueueProcessingCallback(QueueProcessingCallback.LIFO); | |
lifo.process(callback1); | |
lifo.process(callback2); | |
lifo.process(callback3); | |
lifo.process(callback4); | |
lifo.process(callback1); | |
lifo.process(callback2); | |
lifo.process(callback3); | |
lifo.process(callback4); | |
setTimeout(() => { | |
fifo.debug(); | |
lifo.debug(); | |
}, 10000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://codesandbox.io/p/sandbox/bold-yalow-x48l6v