fix: fix circular array splice semantic
authorJérôme Benoit <jerome.benoit@sap.com>
Sat, 29 Jul 2023 13:20:57 +0000 (15:20 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Sat, 29 Jul 2023 13:20:57 +0000 (15:20 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/circular-array.ts
tests/circular-array.test.js

index 40bd19ae0fc74742380979fe05712a5e962251c6..dadfa950043577a66d50387e59af621045bad66e 100644 (file)
@@ -51,18 +51,28 @@ export class CircularArray<T> extends Array<T> {
   }
 
   /** @inheritDoc */
-  public splice (start: number, deleteCount?: number, ...items: T[]): T[] {
-    let itemsRemoved: T[]
+  public splice (
+    start: number,
+    deleteCount?: number,
+    ...items: T[]
+  ): CircularArray<T> {
+    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<T>(
+          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<T>
   }
 
   public resize (size: number): void {
index a86372349ca16ab0985e515cada42c5651904e8d..7e3e96cbee15fd6cdfdf730aacbb4a49849d3401 100644 (file)
@@ -83,9 +83,9 @@ describe('Circular array 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', () => {