Skip to content

Commit

Permalink
Merge pull request #159 from sylvainpolletvillard/fix-array-splice-in…
Browse files Browse the repository at this point in the history
…sert

fix array splice insertion of items
  • Loading branch information
endel authored Nov 5, 2023
2 parents bea23c0 + c957742 commit 6088636
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/types/ArraySchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,10 @@ export class ArraySchema<V = any> implements Array<V>, SchemaDecoderCallbacks {
this.$deleteAt(indexes[i]);
}

for (let i = 0; i < items.length; i++) {
this.setAt(start + i, items[i]);
}

return removedItems;
}

Expand Down
41 changes: 40 additions & 1 deletion test/ArraySchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ describe("ArraySchema Tests", () => {

const removedItems = state.arrayOfPlayers.splice(1);
assert.strictEqual(2, removedItems.length);
assert.deepEqual(['Snake', 'Cyberhawk'], removedItems.map((player) => player.name));
assert.deepStrictEqual(['Snake', 'Cyberhawk'], removedItems.map((player) => player.name));

decodedState.decode(state.encode());

Expand All @@ -456,6 +456,45 @@ describe("ArraySchema Tests", () => {
assert.strictEqual(jake, decodedState.arrayOfPlayers[0]);
});

it("should allow to insert elements with splice", () => {
const state = new State();
const p1 = new Player("Jake")
const p2 = new Player("Snake")
const p3 = new Player("Cyberhawk")
const p4 = new Player("Katarina Lyons")

state.arrayOfPlayers = new ArraySchema(p1, p2)
state.arrayOfPlayers.splice(0, 2, p3, p4)

const decodedState = new State();
decodedState.decode(state.encode());

assert.strictEqual(decodedState.arrayOfPlayers.length, 2);
assert.strictEqual(decodedState.arrayOfPlayers[0].name, "Cyberhawk");
assert.strictEqual(decodedState.arrayOfPlayers[1].name, "Katarina Lyons");
})

it("should adjust the indexes of the elements after a splice", () => {
const state = new State();
const p1 = new Player("Jake")
const p2 = new Player("Snake")
const p3 = new Player("Cyberhawk")
const p4 = new Player("Katarina Lyons")

const newPlayer = new Player("John")

state.arrayOfPlayers = new ArraySchema(p1, p2, p3, p4)
state.arrayOfPlayers.splice(1, 2, newPlayer)

const decodedState = new State();
decodedState.decode(state.encode());

assert.strictEqual(decodedState.arrayOfPlayers.length, 3);
assert.strictEqual(decodedState.arrayOfPlayers[0].name, "Jake");
assert.strictEqual(decodedState.arrayOfPlayers[1].name, "John");
assert.strictEqual(decodedState.arrayOfPlayers[2].name, "Katarina Lyons");
})

it("should allow to push and shift", () => {
const state = new State();
state.arrayOfPlayers = new ArraySchema(
Expand Down

0 comments on commit 6088636

Please sign in to comment.