import {test} from 'node:test';
import assert from 'node:assert/strict';
import {mapLimit} from './main.js';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// fn for the tests: counts the calls running at once, and keeps the highest count.
function counter() {
const seen = {active: 0, most: 0, calls: 0};
seen.fn = async (ms) => {
seen.calls++;
seen.active++;
seen.most = Math.max(seen.most, seen.active);
await sleep(ms);
seen.active--;
return ms * 2;
};
return seen;
}
test('returns the results in the order of items', async () => {
const got = await mapLimit([30, 10, 20], 2, counter().fn);
assert.deepEqual(got, [60, 20, 40], `mapLimit returned ${JSON.stringify(got)}`);
});
test('never runs more than limit calls at once', async () => {
const seen = counter();
await mapLimit([20, 10, 30, 10, 20, 10], 2, seen.fn);
assert.equal(seen.most, 2, `at most ${seen.most} calls ran at once; expected 2`);
});
test('calls fn once for every item, also when limit is larger than the list', async () => {
const seen = counter();
const got = await mapLimit([10, 20], 5, seen.fn);
assert.deepEqual(got, [20, 40], `mapLimit returned ${JSON.stringify(got)}`);
assert.equal(seen.calls, 2, `fn was called ${seen.calls} times; expected 2`);
});
test('an empty list gives an empty array', async () => {
const got = await mapLimit([], 3, counter().fn);
assert.deepEqual(got, [], `mapLimit returned ${JSON.stringify(got)}`);
});