From f69c4304a22b434e310dd7ad7ca99fe9cbf2ea64 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 29 Jul 2023 15:19:37 +0200 Subject: [PATCH] fix: fix circular array splice semantic MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils/CircularArray.ts | 18 ++++++++++++------ test/utils/CircularArray.test.ts | 4 ++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/utils/CircularArray.ts b/src/utils/CircularArray.ts index f87ddd45..bd768673 100644 --- a/src/utils/CircularArray.ts +++ b/src/utils/CircularArray.ts @@ -45,18 +45,24 @@ export class CircularArray extends Array { return concatenatedCircularArray; } - public splice(start: number, deleteCount?: number, ...items: T[]): T[] { - let itemsRemoved: T[]; + public splice(start: number, deleteCount?: number, ...items: T[]): CircularArray { + let itemsRemoved: T[] = []; if (arguments.length >= 3 && deleteCount !== undefined) { - itemsRemoved = super.splice(start, deleteCount); - // FIXME: that makes the items insert not in place - this.push(...items); + itemsRemoved = super.splice(start, deleteCount, ...items); + if (this.length > this.size) { + const itemsOverflowing = super.splice(0, this.length - this.size); + itemsRemoved = new CircularArray( + itemsRemoved.length + itemsOverflowing.length, + ...itemsRemoved, + ...itemsOverflowing, + ); + } } else if (arguments.length === 2) { itemsRemoved = super.splice(start, deleteCount); } else { itemsRemoved = super.splice(start); } - return itemsRemoved; + return itemsRemoved as CircularArray; } public resize(size: number): void { diff --git a/test/utils/CircularArray.test.ts b/test/utils/CircularArray.test.ts index 9af28090..18910d8c 100644 --- a/test/utils/CircularArray.test.ts +++ b/test/utils/CircularArray.test.ts @@ -82,9 +82,9 @@ describe('CircularArray test suite', () => { expect(circularArray).toStrictEqual(new CircularArray(1000, 1, 2, 4, 5)); circularArray = new CircularArray(4, 1, 2, 3, 4); deletedItems = circularArray.splice(2, 1, 5, 6); - expect(deletedItems).toStrictEqual(new CircularArray(1, 3)); + expect(deletedItems).toStrictEqual(new CircularArray(2, 3, 1)); expect(circularArray.length).toBe(4); - expect(circularArray).toStrictEqual(new CircularArray(4, 2, 4, 5, 6)); + expect(circularArray).toStrictEqual(new CircularArray(4, 2, 5, 6, 4)); }); it('Verify that circular array concat works as intended', () => { -- 2.34.1