Skip to content

Commit

Permalink
maxAll
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiancook committed Jun 14, 2024
1 parent 6a09d8f commit ff5bd34
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/tests/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ try {
await import("./iterable-lifecycle");
await import("./blend");
await import("./line");
await import("./max-all");
} catch (error) {
if (error instanceof AggregateError) {
console.error(error.errors);
Expand Down
39 changes: 39 additions & 0 deletions src/tests/max-all.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

import {union} from "@virtualstate/union";

{

async function * maxAll<T>(fns: Iterable<() => Promise<T>>, max: number) {
let inProgress: Promise<T>[] = [];
for (const next of fns) {
while (inProgress.length >= max) {
console.log("Waiting for", inProgress);
await Promise.race(inProgress);
}
const promise = next();
inProgress.push(promise);
promise.finally(() => {
inProgress = inProgress.filter(p => p !== promise);
});
console.log({ inProgress });
yield {
async *[Symbol.asyncIterator]() {
yield promise;
}
};
}
}

async function sleep<T>(wait = 10, arg: T) {
return new Promise<T>(resolve => setTimeout(resolve, wait, arg));
}

for await (const partial of union(maxAll([
() => sleep(10, 1),
() => sleep(10, 2),
() => sleep(10, 3),
() => sleep(10, 4)
], 2))) {
console.log({ partial });
}
}

0 comments on commit ff5bd34

Please sign in to comment.