Skip to content

Instantly share code, notes, and snippets.

@ajitid
Last active March 9, 2023 12:05
Show Gist options
  • Save ajitid/b20c99398f4c1fce2941d38f6d5c27ed to your computer and use it in GitHub Desktop.
Save ajitid/b20c99398f4c1fce2941d38f6d5c27ed to your computer and use it in GitHub Desktop.
Max async tasks - interview practice solution (NOT for prod use)
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));
}
@ajitid
Copy link
Author

ajitid commented May 30, 2022

A sophisticated way to solve this can be found here https://github.com/ajitid/fzf-for-js/tree/experiments/with-web-workers/src/utils

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment