Skip to content

Commit e77f3d1

Browse files
authored
fix(stats): avoid max argument overflow (#44494)
1 parent 00e05db commit e77f3d1

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

lib/util/stats.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,20 @@ describe('util/stats', () => {
5050
totalMs: 700,
5151
});
5252
});
53+
54+
it('does not overflow the call stack for large datasets', () => {
55+
const res = makeTimingReport(
56+
Array.from<number>({ length: 200_000 }).fill(1),
57+
);
58+
59+
expect(res).toEqual({
60+
avgMs: 1,
61+
count: 200_000,
62+
maxMs: 1,
63+
medianMs: 1,
64+
totalMs: 200_000,
65+
});
66+
});
5367
});
5468

5569
describe('LookupStats', () => {

lib/util/stats.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ export function makeTimingReport(data: number[]): TimingStatsReport {
1717
const count = data.length;
1818
const totalMs = data.reduce((a, c) => a + c, 0);
1919
const avgMs = count ? Math.round(totalMs / count) : 0;
20-
const maxMs = Math.max(0, ...data);
20+
let maxMs = 0;
21+
for (const duration of data) {
22+
maxMs = Math.max(maxMs, duration);
23+
}
2124
const sorted = data.sort((a, b) => a - b);
2225
const medianMs = count ? sorted[Math.floor(count / 2)] : 0;
2326
return { count, avgMs, medianMs, maxMs, totalMs };

0 commit comments

Comments
 (0)