Last active
March 9, 2023 12:05
-
-
Save ajitid/b20c99398f4c1fce2941d38f6d5c27ed to your computer and use it in GitHub Desktop.
Max async tasks - interview practice solution (NOT for prod use)
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
type AsyncFn = () => Promise<unknown>; | |
class AsyncWorkers { | |
private queue: Array<AsyncFn> = []; | |
private workersAvailable; | |
constructor(workersCount: number) { | |
this.workersAvailable = workersCount; | |
} | |
private doTask() { | |
if (!this.workersAvailable || !this.queue.length) return; | |
const task = this.queue.shift(); | |
if (!task) return; | |
this.workersAvailable--; | |
task().then(() => { | |
this.workersAvailable++; | |
this.doTask(); | |
}); | |
} | |
pushTask(fn: AsyncFn) { | |
this.queue.push(fn); | |
if (this.workersAvailable) { | |
this.doTask(); | |
} | |
} | |
} | |
function asyncFn(v: number) { | |
return function () { | |
return new Promise((resolve) => { | |
setTimeout(function () { | |
console.log(v); | |
resolve(v); | |
}, v * 1000); | |
}); | |
}; | |
} | |
const WORKER_POOL_LENGTH = 2; | |
const w = new AsyncWorkers(WORKER_POOL_LENGTH); | |
for (let i = 0; i < 30; i++) { | |
w.pushTask(asyncFn(1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A sophisticated way to solve this can be found here https://github.com/ajitid/fzf-for-js/tree/experiments/with-web-workers/src/utils