EN
JavaScript - create custom iterator for any Object
9 points
In this short article we would like to show how to create custom iterator for any Object
in JavaScript.
Motivation to create own one iterator may be:
- custom behaving of iterator on existing iterable objects, e.g. Array, etc.
- support for
for..of
loops on non-iterable objects.
In the below we create default iterator equivalent that may be base for the target version.
Practical example:
xxxxxxxxxx
1
function ArrayIterator(array) {
2
let index = 0;
3
this.next = function() {
4
if (index < array.length) {
5
const result = {
6
done: false,
7
value: array[index]
8
};
9
index += 1;
10
return result;
11
} else {
12
return {
13
done: true
14
};
15
}
16
};
17
this[Symbol.iterator] = function() {
18
return this;
19
};
20
}
21
22
23
// Usage example:
24
25
const array = [1, 2, 3];
26
const iterator = new ArrayIterator(array);
27
28
for (const item of iterator) {
29
console.log(item);
30
}
Note:
Symbol
function andfor..of
loop syntax were introduced in ES6 (ES2015).
xxxxxxxxxx
1
class ArrayIterator {
2
#index;
3
#array;
4
constructor(array) {
5
this.#index = 0;
6
this.#array = array;
7
}
8
next() {
9
if (this.#index < this.#array.length) {
10
const result = {
11
done: false,
12
value: this.#array[this.#index]
13
};
14
this.#index += 1;
15
return result;
16
} else {
17
return {
18
done: true
19
};
20
}
21
};
22
[Symbol.iterator]() {
23
return this;
24
};
25
}
26
27
28
// Usage example:
29
30
const array = [1, 2, 3];
31
const iterator = new ArrayIterator(array);
32
33
for (const item of iterator) {
34
console.log(item);
35
}