Skip to content

Commit 273219e

Browse files
committed
Polyfill Iterator.prototype.forEach for node 20
1 parent 9499875 commit 273219e

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

tests/tests/src/core/Core_IteratorTests.mjs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,24 @@ let syncResult = {
1616
contents: undefined
1717
};
1818

19+
if (!Iterator.prototype.forEach) {
20+
Iterator.prototype.forEach = function forEach(callback, thisArg) {
21+
if (typeof callback !== 'function') {
22+
throw new TypeError(callback + ' is not a function');
23+
}
24+
25+
let index = 0;
26+
let result = this.next();
27+
28+
while (!result.done) {
29+
callback.call(thisArg, result.value, index, this);
30+
result = this.next();
31+
index++;
32+
}
33+
};
34+
}
35+
;
36+
1937
iterator.forEach(v => {
2038
if (v === "b") {
2139
syncResult.contents = "b";
@@ -27,7 +45,7 @@ iterator.forEach(v => {
2745
Test.run([
2846
[
2947
"Core_IteratorTests.res",
30-
19,
48+
38,
3149
20,
3250
34
3351
],
@@ -59,7 +77,7 @@ await Stdlib_AsyncIterator.forEach(asyncIterator, v => {
5977
Test.run([
6078
[
6179
"Core_IteratorTests.res",
62-
42,
80+
61,
6381
20,
6482
35
6583
],
@@ -95,7 +113,7 @@ await Stdlib_AsyncIterator.forEach(asyncIterator$1, v => {
95113
Test.run([
96114
[
97115
"Core_IteratorTests.res",
98-
67,
116+
86,
99117
20,
100118
54
101119
],

tests/tests/src/core/Core_IteratorTests.res

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,25 @@ let iterator: Iterator.t<string> = %raw(`
1010

1111
let syncResult = ref(None)
1212

13+
%%raw(`
14+
if (!Iterator.prototype.forEach) {
15+
Iterator.prototype.forEach = function forEach(callback, thisArg) {
16+
if (typeof callback !== 'function') {
17+
throw new TypeError(callback + ' is not a function');
18+
}
19+
20+
let index = 0;
21+
let result = this.next();
22+
23+
while (!result.done) {
24+
callback.call(thisArg, result.value, index, this);
25+
result = this.next();
26+
index++;
27+
}
28+
};
29+
}
30+
`)
31+
1332
iterator->Iterator.forEach(v => {
1433
if v == "b" {
1534
syncResult.contents = Some("b")

0 commit comments

Comments
 (0)