Fix stack overflow in diff() for large element counts

This commit is contained in:
Kalle
2026-06-20 14:44:28 +03:00
parent dd5d98a243
commit cd05d444c3
2 changed files with 9 additions and 1 deletions

View File

@@ -36,6 +36,12 @@ describe("diff", () => {
const result = diff(arr1, arr2);
expect(result).toEqual([]);
});
it("should not overflow the stack for very large counts", () => {
const arr2 = new Array(200_000).fill(1);
const result = diff([], arr2);
expect(result).toHaveLength(200_000);
});
});
describe("mostPopularArrayElement", () => {

View File

@@ -53,7 +53,9 @@ export function diff<T extends string | number>(arr1: T[], arr2: T[]): T[] {
const result: T[] = [];
for (const [element, count] of diff) {
result.push(...new Array(count).fill(element));
for (let i = 0; i < count; i++) {
result.push(element);
}
}
return result;