42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
function createPlanTodayReadiness({ identity, inspect, concurrency = 3 }) {
|
|
const workerCount = Math.max(1, Math.floor(Number(concurrency) || 1));
|
|
let generation = 0;
|
|
|
|
async function run(items) {
|
|
const runGeneration = ++generation;
|
|
const candidates = Array.from(items || []);
|
|
const results = new Array(candidates.length);
|
|
let next = 0;
|
|
|
|
async function worker() {
|
|
while (next < candidates.length) {
|
|
const index = next;
|
|
next += 1;
|
|
const item = candidates[index];
|
|
let result;
|
|
try {
|
|
result = await inspect(item);
|
|
} catch (_error) {
|
|
result = { status:'unverified' };
|
|
}
|
|
results[index] = [identity(item), result];
|
|
}
|
|
}
|
|
|
|
await Promise.all(Array.from(
|
|
{ length:Math.min(workerCount, candidates.length) },
|
|
() => worker(),
|
|
));
|
|
if (runGeneration !== generation) return null;
|
|
return Object.fromEntries(results);
|
|
}
|
|
|
|
function cancel() {
|
|
generation += 1;
|
|
}
|
|
|
|
return { run, cancel };
|
|
}
|
|
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = createPlanTodayReadiness;
|