← run

js-09-pool

0.000
0/1 tests· concurrency
Challenge · difficulty 5/5
# Concurrency-limited async pool

Implement an ES module **`solution.js`** (no external libraries):

```js
export async function pool(thunks, concurrency) { /* ... */ }
```

`thunks` is an array of zero-argument functions, each returning a promise (async thunks).
Run them with **at most `concurrency` running at the same time**, and resolve with an array
of their results **in the original order of `thunks`** (not completion order).

Requirements:
- The result at index `i` must be the resolved value of `thunks[i]`.
- At no point may more than `concurrency` thunks be in flight simultaneously.
- As soon as one thunk settles, the next pending thunk should start (keep the pool full).
- An empty `thunks` array resolves to `[]`.
- You may assume `concurrency >= 1`.

Notes:
- Do not simply run everything via `Promise.all(thunks.map(...))` — that ignores the limit.
- You do not need to handle rejections specially (a rejecting thunk may reject the pool).

Example:
```js
const order = [];
const make = (id, ms) => () =>
  new Promise((res) => setTimeout(() => { order.push(id); res(id); }, ms));
await pool([make("a", 30), make("b", 10), make("c", 20)], 2);
// => ["a", "b", "c"]  (results in original order, regardless of finish order)
```
tests/solution.test.js
import { test } from "node:test";
import { strict as assert } from "node:assert";
import { pool } from "./solution.js";

const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

// Build instrumented thunks that track peak concurrency.
function makeTracker() {
  const state = { active: 0, peak: 0, starts: [] };
  const thunk = (id, ms) => async () => {
    state.active++;
    state.peak = Math.max(state.peak, state.active);
    state.starts.push(id);
    await sleep(ms);
    state.active--;
    return id;
  };
  return { state, thunk };
}

test("results are returned in original order, not completion order", async () => {
  const { thunk } = makeTracker();
  // 'a' is slowest but must still come first in the results.
  const out = await pool([thunk("a", 30), thunk("b", 5), thunk("c", 15)], 3);
  assert.deepEqual(out, ["a", "b", "c"]);
});

test("peak concurrency never exceeds the limit", async () => {
  const { state, thunk } = makeTracker();
  const thunks = [];
  for (let i = 0; i < 10; i++) thunks.push(thunk(i, 10));
  const out = await pool(thunks, 3);
  assert.deepEqual(out, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  assert.ok(state.peak <= 3, `peak was ${state.peak}, expected <= 3`);
  assert.equal(state.peak, 3); // pool should actually reach the limit
});

test("concurrency of 1 runs strictly sequentially", async () => {
  const { state, thunk } = makeTracker();
  const thunks = [thunk("x", 10), thunk("y", 10), thunk("z", 10)];
  const out = await pool(thunks, 1);
  assert.deepEqual(out, ["x", "y", "z"]);
  assert.equal(state.peak, 1);
});

test("empty thunks -> empty array", async () => {
  const out = await pool([], 4);
  assert.deepEqual(out, []);
});

test("concurrency larger than number of thunks", async () => {
  const { state, thunk } = makeTracker();
  const thunks = [thunk(1, 5), thunk(2, 5)];
  const out = await pool(thunks, 10);
  assert.deepEqual(out, [1, 2]);
  assert.equal(state.peak, 2);
});

test("all thunks actually run exactly once", async () => {
  let count = 0;
  const thunks = [];
  for (let i = 0; i < 6; i++) {
    thunks.push(async () => {
      count++;
      await sleep(2);
      return i * i;
    });
  }
  const out = await pool(thunks, 2);
  assert.deepEqual(out, [0, 1, 4, 9, 16, 25]);
  assert.equal(count, 6);
});

test("pool keeps the slots full as tasks finish", async () => {
  // Mix of fast and slow tasks; with limit 2, a fast finisher should let a new
  // task start while a slow one is still running -> peak hits 2 repeatedly.
  const { state, thunk } = makeTracker();
  const thunks = [
    thunk("a", 40),
    thunk("b", 5),
    thunk("c", 5),
    thunk("d", 5),
  ];
  const out = await pool(thunks, 2);
  assert.deepEqual(out, ["a", "b", "c", "d"]);
  assert.equal(state.peak, 2);
});
Proposed solution
```js
const thunks = [ [ 'a', 'b', 'c' ] ];
const concurrency = 1;
const thunks = [ [ 'a', 'b', 'c' ] ];
await pool([ 'a', 'b', 'c' ], 2 );
```

Test output (stdout)

TAP version 13
# file:///tmp/llmlab-js-09-pool-t2mog161/solution.js:3
# const thunks = [ [ 'a', 'b', 'c' ] ];
#       ^
# SyntaxError: Identifier 'thunks' has already been declared
#     at compileSourceTextModule (node:internal/modules/esm/utils:318:16)
#     at ModuleLoader.moduleStrategy (node:internal/modules/esm/translators:90:18)
#     at \#translate (node:internal/modules/esm/loader:435:20)
#     at afterLoad (node:internal/modules/esm/loader:491:29)
#     at ModuleLoader.loadAndTranslate (node:internal/modules/esm/loader:496:12)
#     at \#getOrCreateModuleJobAfterResolve (node:internal/modules/esm/loader:549:36)
#     at afterResolve (node:internal/modules/esm/loader:597:52)
#     at ModuleLoader.getOrCreateModuleJob (node:internal/modules/esm/loader:603:12)
#     at ModuleJob.syncLink (node:internal/modules/esm/module_job:163:33)
#     at ModuleJob.link (node:internal/modules/esm/module_job:253:17)
# Node.js v24.16.0
# Subtest: solution.test.js
not ok 1 - solution.test.js
  ---
  duration_ms: 16.626933
  type: 'test'
  location: '/tmp/llmlab-js-09-pool-t2mog161/solution.test.js:1:1'
  failureType: 'testCodeFailure'
  exitCode: 1
  signal: ~
  error: 'test failed'
  code: 'ERR_TEST_FAILURE'
  ...
1..1
# tests 1
# suites 0
# pass 0
# fail 1
# cancelled 0
# skipped 0
# todo 0
# duration_ms 19.805877