Last active
March 10, 2025 07:57
-
-
Save AimWhy/9eac11f32bbd63293fc35b8ff7c0f842 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 workerPool = (concurrentCount) => { | |
| const queue = []; | |
| let max = Math.max(concurrentCount, 1); | |
| const resetMax = (m) => { | |
| max = Math.max(m, 1); | |
| checkQueue(); | |
| }; | |
| const checkQueue = () => { | |
| let len = Math.min(max, queue.length); | |
| while (len && !queue[len - 1].isRunning) { | |
| startItem(queue[len - 1]); | |
| } | |
| }; | |
| const startItem = (item) => { | |
| item.isRunning = true; | |
| item.workFn().then(item.resolve).catch(item.reject).finally(() => { | |
| const index = queue.indexOf(item); | |
| queue.splice(index, 1); | |
| checkQueue(); | |
| }); | |
| }; | |
| const runWork = (workFn) => { | |
| const item = { | |
| workFn, | |
| isRunning: false, | |
| ...Promise.withResolvers() | |
| } | |
| queue.push(item); | |
| checkQueue(); | |
| return item.promise; | |
| }; | |
| return { | |
| runWork, | |
| resetMax, | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment