mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 23:07:35 +00:00
LibJS: Implement Iterator.prototype.forEach
This commit is contained in:
parent
35380b2aef
commit
134bb44ca0
3 changed files with 139 additions and 0 deletions
|
@ -0,0 +1,94 @@
|
|||
describe("errors", () => {
|
||||
test("called with non-callable object", () => {
|
||||
expect(() => {
|
||||
Iterator.prototype.forEach(Symbol.hasInstance);
|
||||
}).toThrowWithMessage(TypeError, "fn is not a function");
|
||||
});
|
||||
|
||||
test("iterator's next method throws", () => {
|
||||
function TestError() {}
|
||||
|
||||
class TestIterator extends Iterator {
|
||||
next() {
|
||||
throw new TestError();
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestIterator().forEach(() => 0);
|
||||
}).toThrow(TestError);
|
||||
});
|
||||
|
||||
test("value returned by iterator's next method throws", () => {
|
||||
function TestError() {}
|
||||
|
||||
class TestIterator extends Iterator {
|
||||
next() {
|
||||
return {
|
||||
done: false,
|
||||
get value() {
|
||||
throw new TestError();
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestIterator().forEach(() => 0);
|
||||
}).toThrow(TestError);
|
||||
});
|
||||
|
||||
test("for-each function throws", () => {
|
||||
function TestError() {}
|
||||
|
||||
class TestIterator extends Iterator {
|
||||
next() {
|
||||
return {
|
||||
done: false,
|
||||
value: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
expect(() => {
|
||||
new TestIterator().forEach(() => {
|
||||
throw new TestError();
|
||||
});
|
||||
}).toThrow(TestError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normal behavior", () => {
|
||||
test("length is 1", () => {
|
||||
expect(Iterator.prototype.forEach).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("for-each function sees every value", () => {
|
||||
function* generator() {
|
||||
yield "a";
|
||||
yield "b";
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
|
||||
generator().forEach((value, index) => {
|
||||
++count;
|
||||
|
||||
switch (index) {
|
||||
case 0:
|
||||
expect(value).toBe("a");
|
||||
break;
|
||||
case 1:
|
||||
expect(value).toBe("b");
|
||||
break;
|
||||
default:
|
||||
expect().fail(`Unexpected reducer invocation: value=${value} index=${index}`);
|
||||
break;
|
||||
}
|
||||
|
||||
return value;
|
||||
}, "");
|
||||
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue