| 1 |
/* |
| 2 |
* async-series-loop-hook |
| 3 |
* |
| 4 |
* AsyncSeriesLoopHook is the async cousin of SyncLoopHook - re-runs the |
| 5 |
* tap chain while any tap signals "loop again" (non-undefined value). |
| 6 |
* Covers 0 reloops (single pass) and a small multi-pass case. |
| 7 |
*/ |
| 8 |
|
| 9 |
import tapable from "../../../lib/index.js"; |
| 10 |
|
| 11 |
const { AsyncSeriesLoopHook } = tapable; |
| 12 |
|
| 13 |
function makeHook(numTaps, reloops) { |
| 14 |
const hook = new AsyncSeriesLoopHook(["state"]); |
| 15 |
for (let i = 0; i < numTaps; i++) { |
| 16 |
const idx = i; |
| 17 |
hook.tap(`plugin-${idx}`, (state) => { |
| 18 |
if (state.counts[idx] < reloops) { |
| 19 |
state.counts[idx]++; |
| 20 |
return true; |
| 21 |
} |
| 22 |
return undefined; |
| 23 |
}); |
| 24 |
} |
| 25 |
hook.callAsync( |
| 26 |
{ counts: Array.from({ length: numTaps }, () => reloops) }, |
| 27 |
() => {} |
| 28 |
); |
| 29 |
return hook; |
| 30 |
} |
| 31 |
|
| 32 |
function resetState(state) { |
| 33 |
for (let i = 0; i < state.counts.length; i++) state.counts[i] = 0; |
| 34 |
} |
| 35 |
|
| 36 |
const INNER_ITERATIONS = 100; |
| 37 |
|
| 38 |
function runBatch(hook, state) { |
| 39 |
return new Promise((resolve, reject) => { |
| 40 |
let remaining = INNER_ITERATIONS; |
| 41 |
const next = (err) => { |
| 42 |
if (err) return reject(err); |
| 43 |
resetState(state); |
| 44 |
if (--remaining === 0) return resolve(); |
| 45 |
hook.callAsync(state, next); |
| 46 |
}; |
| 47 |
resetState(state); |
| 48 |
hook.callAsync(state, next); |
| 49 |
}); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* @param {import('tinybench').Bench} bench |
| 54 |
*/ |
| 55 |
export default function register(bench) { |
| 56 |
for (const [n, reloops] of [ |
| 57 |
[3, 0], |
| 58 |
[3, 2], |
| 59 |
[10, 0] |
| 60 |
]) { |
| 61 |
const hook = makeHook(n, reloops); |
| 62 |
const state = { counts: Array.from({ length: n }, () => 0) }; |
| 63 |
bench.add(`async-series-loop-hook: ${n} taps, ${reloops} reloops`, () => |
| 64 |
runBatch(hook, state) |
| 65 |
); |
| 66 |
} |
| 67 |
} |