Skip to content

Commit

Permalink
Merge pull request #168 from sylvainpolletvillard/fix-array-at
Browse files Browse the repository at this point in the history
fix ArraySchema#at with negative indexes
  • Loading branch information
endel committed Apr 5, 2024
2 parents 81932bc + d0e0502 commit a1eb541
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/types/ArraySchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,13 @@ export class ArraySchema<V = any> implements Array<V>, SchemaDecoderCallbacks {
//
// FIXME: this should be O(1)
//

index = Math.trunc(index) || 0;
// Allow negative indexing from the end
if (index < 0) index += this.length;
// OOB access is guaranteed to return undefined
if (index < 0 || index >= this.length) return undefined;

const key = Array.from(this.$items.keys())[index];
return this.$items.get(key);
}
Expand Down
10 changes: 10 additions & 0 deletions test/ArraySchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1495,6 +1495,16 @@ describe("ArraySchema Tests", () => {

assert.deepEqual([1,2,3], arr.toJSON());
});

it("#at()", () => {
const arr = new ArraySchema<number>(1,2,3,4,5);
assert.strictEqual(1, arr.at(0));
assert.strictEqual(3, arr.at(2));
assert.strictEqual(5, arr.at(-1));
assert.strictEqual(1, arr.at(-5));
assert.strictEqual(undefined, arr.at(5));
assert.strictEqual(undefined, arr.at(-6));
});
})

describe("ArraySchema <-> Array type interchangability", () => {
Expand Down

0 comments on commit a1eb541

Please sign in to comment.