Interesting patterns from LLM generated code
Published on
While writing the script to generate lighter-weight webp images for this site, I was asking an LLM for various worker-pool implementations in javascript. And an interesting pattern popped up, which I'm trying to google around and I guess the first reference I see is p-limit
let nextIndex = 0;
async function worker() {
while(true) {
const index = nextIndex++;
if (index >= items.length) {
return;
}
results[index] = await doWork();
}
}
const workers = Array.from({ length: Math.min(concurrencyLimit, items.length) }, () => worker());
await Promise.all(workers);
return results;
The Array.from to limit the number of calls to worker() is interesting. Since javascript is synchronous, the incrementing of nextIndex is also safe.