1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 17:57:35 +00:00

LibJS: Add TypedArray.prototype.@@iterator

This commit is contained in:
Luke Wilde 2021-12-21 14:26:53 +00:00 committed by Linus Groh
parent 4fe47ed86e
commit 6d5531112f
2 changed files with 92 additions and 0 deletions

View file

@ -0,0 +1,89 @@
const TYPED_ARRAYS = [
Uint8Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
Int8Array,
Int16Array,
Int32Array,
Float32Array,
Float64Array,
];
const BIGINT_TYPED_ARRAYS = [BigUint64Array, BigInt64Array];
const ALL_TYPED_ARRAYS = TYPED_ARRAYS.concat(BIGINT_TYPED_ARRAYS);
describe("correct behavior", () => {
test("length is 0", () => {
ALL_TYPED_ARRAYS.forEach(T => {
expect(T.prototype[Symbol.iterator]).toHaveLength(0);
});
});
test("same value as %TypedArray%.prototype.values", () => {
ALL_TYPED_ARRAYS.forEach(T => {
expect(T.prototype[Symbol.iterator]).toBe(T.prototype.values);
});
});
test("basic functionality", () => {
TYPED_ARRAYS.forEach(T => {
const typedArray = new T([1, 2, 3]);
const iterator = typedArray[Symbol.iterator]();
expect(iterator.next()).toEqual({ value: 1, done: false });
expect(iterator.next()).toEqual({ value: 2, done: false });
expect(iterator.next()).toEqual({ value: 3, done: false });
expect(iterator.next()).toEqual({ value: undefined, done: true });
expect(iterator.next()).toEqual({ value: undefined, done: true });
expect(iterator.next()).toEqual({ value: undefined, done: true });
});
BIGINT_TYPED_ARRAYS.forEach(T => {
const typedArray = new T([1n, 2n, 3n]);
const iterator = typedArray[Symbol.iterator]();
expect(iterator.next()).toEqual({ value: 1n, done: false });
expect(iterator.next()).toEqual({ value: 2n, done: false });
expect(iterator.next()).toEqual({ value: 3n, done: false });
expect(iterator.next()).toEqual({ value: undefined, done: true });
expect(iterator.next()).toEqual({ value: undefined, done: true });
expect(iterator.next()).toEqual({ value: undefined, done: true });
});
});
test("can be iterated with for-of", () => {
TYPED_ARRAYS.forEach(T => {
const typedArray = new T([1, 2, 3]);
const result = [];
for (const value of typedArray) result.push(value);
expect(result).toHaveLength(3);
expect(result[0]).toBe(1);
expect(result[1]).toBe(2);
expect(result[2]).toBe(3);
});
BIGINT_TYPED_ARRAYS.forEach(T => {
const typedArray = new T([1n, 2n, 3n]);
const result = [];
for (const value of typedArray) result.push(value);
expect(result).toHaveLength(3);
expect(result[0]).toBe(1n);
expect(result[1]).toBe(2n);
expect(result[2]).toBe(3n);
});
});
});
describe("errors", () => {
test("this value must be a TypedArray object", () => {
ALL_TYPED_ARRAYS.forEach(T => {
expect(() => {
T.prototype[Symbol.iterator].call({});
}).toThrowWithMessage(TypeError, "Not an object of type TypedArray");
});
});
});