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:
// ONLINE-RUNNER:browser;
function ArrayIterator(array) {
let index = 0;
this.next = function() {
if (index < array.length) {
const result = {
done: false,
value: array[index]
};
index += 1;
return result;
} else {
return {
done: true
};
}
};
this[Symbol.iterator] = function() {
return this;
};
}
// Usage example:
const array = [1, 2, 3];
const iterator = new ArrayIterator(array);
for (const item of iterator) {
console.log(item);
}
Note:
Symbol
function andfor..of
loop syntax were introduced in ES6 (ES2015).
Class based solution
// ONLINE-RUNNER:browser;
class ArrayIterator {
#index;
#array;
constructor(array) {
this.#index = 0;
this.#array = array;
}
next() {
if (this.#index < this.#array.length) {
const result = {
done: false,
value: this.#array[this.#index]
};
this.#index += 1;
return result;
} else {
return {
done: true
};
}
};
[Symbol.iterator]() {
return this;
};
}
// Usage example:
const array = [1, 2, 3];
const iterator = new ArrayIterator(array);
for (const item of iterator) {
console.log(item);
}