Skip to content

Commit

Permalink
add more test
Browse files Browse the repository at this point in the history
  • Loading branch information
andykswong committed Mar 17, 2024
1 parent f8f192f commit db07987
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
29 changes: 28 additions & 1 deletion js/wasm/__tests__/vec.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,40 @@
import { expectArrayEqual } from '../../__tests__/test-utils.ts';
import { Mat2, Mat3, Mat4 } from '../mat.ts';
import { getMemoryView } from '../memory.ts';
import { Vec2, Vec3, Vec4 } from '../vec.ts';

describe('Vec2', () => {
test('constructor', () => {
using v = new Vec2();
using v2 = new Vec2(1, 2);
expectArrayEqual(v, [0, 0]);
});

test('free', () => {
const v2 = new Vec2(1, 2);
expectArrayEqual(v2, [1, 2]);
v2.free();
expect(v2.valid).toBe(false);
expectArrayEqual(v2, []);
});

test('ArrayBufferView', () => {
const v = new Vec2(1, 2);
expect(v.byteLength).toBe(16);
expect(v.buffer).toBe(getMemoryView().buffer);
});

test('copy', () => {
const v = new Vec2(3, 5);
const v2 = new Vec2(7, 9);
v.copy(v2);
expectArrayEqual(v, v2);
});

test('at', () => {
const v = new Vec2(3, 5);
expect(v.at(0)).toBe(3);
expect(v.at(1)).toBe(5);
expect(v.at(2)).toBeUndefined();
});

test('set', () => {
Expand Down
6 changes: 4 additions & 2 deletions js/wasm/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ export interface ManagedBufferView<N extends number = number> extends ArrayBuffe
export abstract class ManagedFloat64Array<N extends number = number>
implements ManagedBufferView<N>, Iterable<number> {

public constructor( public byteOffset: number) {
public constructor(public byteOffset: number) {
register(this);
}

public *[Symbol.iterator](): Iterator<number> {
if (!this.valid) { return; }
const view = getMemoryView();
const offset = (this.byteOffset / BYTES_PER_FLOAT64) | 0;
for (let i = 0; i < this.length && offset + i < view.length; i++) {
Expand All @@ -55,6 +56,7 @@ export abstract class ManagedFloat64Array<N extends number = number>

/** Gets the value at given index. */
public at(index: number): number | undefined {
if (index < 0 || index >= this.length) { return; }
return getMemoryView().at((this.byteOffset / BYTES_PER_FLOAT64 + index) | 0);
}

Expand Down Expand Up @@ -86,7 +88,7 @@ export abstract class ManagedFloat64Array<N extends number = number>
}

public get valid(): boolean {
return this.byteOffset > 0;
return this.byteOffset >= 0;
}

public abstract readonly length: N;
Expand Down

0 comments on commit db07987

Please sign in to comment.