Skip to content

Commit

Permalink
Add Float16Array#withAt
Browse files Browse the repository at this point in the history
  • Loading branch information
petamoriken committed Oct 15, 2021
1 parent 2fbb0a3 commit 916f227
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Float16Array.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,27 @@ export class Float16Array extends Uint16Array {
return convertToNumber(this[k]);
}

/** @see https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.withAt */
withAt(index, value) {
assertFloat16BitsArray(this);

const length = this.length;
const relativeIndex = ToIntegerOrInfinity(index);
const k = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;

if (k < 0 || k >= length) {
throw new RangeError("Invalid index");
}

const uint16 = new Uint16Array(this.buffer, this.byteOffset, this.length);
const proxy = new Float16Array(uint16.slice().buffer);
const float16bitsArray = getFloat16BitsArrayFromFloat16Array(proxy);

float16bitsArray[k] = roundToFloat16Bits(value);

return proxy;
}

/** @see https://tc39.es/ecma262/#sec-%typedarray%.prototype.map */
map(callback, ...opts) {
assertFloat16BitsArray(this);
Expand Down
40 changes: 40 additions & 0 deletions test/Float16Array.js
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,47 @@ describe("Float16Array", () => {
assert.throws(() => { float16.at(BigInt(0), 0); }, TypeError);
}
});
});

describe("#withAt()", () => {

it("property `name` is 'withAt'", () => {
assert( Float16Array.prototype.withAt.name === "withAt" );
});

it("property `length` is 1", () => {
assert( Float16Array.prototype.withAt.length === 2 );
});

it("create Array", () => {
const float16_1 = new Float16Array([1, 2, 3]);
const float16_2 = float16_1.withAt(1, 4);

assert( float16_1.buffer !== float16_2.buffer );
assert.equalFloat16ArrayValues( float16_1, [1, 2, 3] );
assert.equalFloat16ArrayValues( float16_2, [1, 4, 3] );

const float16_3 = float16_1.withAt(-1, 4);

assert( float16_1.buffer !== float16_3.buffer );
assert.equalFloat16ArrayValues( float16_1, [1, 2, 3] );
assert.equalFloat16ArrayValues( float16_3, [1, 2, 4] );
});

it("throw Error with invalid index", () => {
const float16 = new Float16Array([1, 2, 3]);

// out of range
assert.throws(() => { float16.withAt(5, 0); }, RangeError);
assert.throws(() => { float16.withAt(-5, 0); }, RangeError);

assert.throws(() => { float16.withAt(Symbol(), 0); }, TypeError);

// Safari 13 doesn't have BigInt
if (typeof BigInt !== "undefined") {
assert.throws(() => { float16.withAt(BigInt(0), 0); }, TypeError);
}
});
});

describe("#map()", () => {
Expand Down

0 comments on commit 916f227

Please sign in to comment.