Skip to content

Commit

Permalink
Added array at method
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderOMara committed Dec 16, 2024
1 parent 0879600 commit 82d7bdf
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
19 changes: 19 additions & 0 deletions arr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { int8 } from './int/8.ts';
import { pointer } from './ptr.ts';
import { Struct } from './struct.ts';
import { getByteLength, getByteOffset } from './util.ts';
import { Uint8Ptr } from './mod.ts';

class Foo extends Struct {
declare public bar: number;
Expand Down Expand Up @@ -98,6 +99,24 @@ Deno.test('array: Symbol.iterator', () => {
}
});

Deno.test('array: at', () => {
const jsar = [1, 2, 3, 4];
const data = new Uint8Array(jsar);
const Four = array(Uint8Ptr, 4);
const four = new Four(data.buffer);

for (
const index of [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10],
[Infinity, -Infinity, NaN, Number.EPSILON, -Number.EPSILON],
[1.1, 0.5, -1.1, -0.5, -0],
].flat()
) {
assertStrictEquals(four.at(index), jsar.at(index), `at(${index})`);
}
});

Deno.test('array: extend', () => {
// Weird but not invalid.
class FooExtra extends Foo4 {
Expand Down
15 changes: 15 additions & 0 deletions arr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ export interface Arr<T = never> extends Ptr<T>, Type {
*/
readonly length: number;

/**
* Get value at index.
*
* @param i Index, can be negative.
*/
at(i: number): T | undefined;

/**
* Array iterator.
*/
Expand Down Expand Up @@ -135,6 +142,14 @@ export function array<T extends Type>(
return length;
}

public at(i: number): T | undefined {
i ||= 0;
i -= i % 1;
if ((i < 0 ? i += length : 0) >= 0 && i < length) {
return this[i];
}
}

public static readonly BYTE_LENGTH = (
Ptr.BYTES_PER_ELEMENT * length
);
Expand Down

0 comments on commit 82d7bdf

Please sign in to comment.