Introduction
In computer programming, an iterator is an object that enables a programmer to traverse a container, mainly an Array or list of items.
In JavaScript (ES2015 onwards) Symbol.iterator is there to convert an array into iterable, which was not present in older versions of JavaScript.
Let's discuss how to create a custom iterator using JavaScript (ES5).
Description
Let's first create a function which will convert the input array into an iterable.
- function iterator(array) {
- var currentIndex = -1;
- return {
- next: function() {
- currentIndex = currentIndex + 1;
- return currentIndex < array.length ? {
- value: array[currentIndex],
- done: false
- } : {
- value: "index out of range",
- done: true
- };
- },
- previous: function() {
- currentIndex = currentIndex - 1;
- return currentIndex >= 0 ? {
- value: array[currentIndex],
- done: false
- } : {
- value: "index out of range",
- done: true
- };
- }
- };
- }
The above function is having 2 inner functions - next and previous. These functions ensure that we can move forward and backward in an iterable from its current position. These functions return the Value and Done.
- Value represents the next or previous value in the array.
- Done represents the status, whether the iteration is complete or not.
Let's see an example.
I have created an array and assigned some values to it.
- var a = [];
- a[0] = 1;
- a[1] = 2;
- a[2] = 3;
- a[3] = 4;
Let's make it iterable.
- var iterable = iterator(a);
- var current = iterable.next();
- while (!current.done) {
- console.log(current.value);
- current = iterable.next();
- }
2
3
4
Let's go back and forth in the array now.
- var res = iterator(a);
- console.log(res);
- console.log(res.next().value);
- console.log(res.next().value);
- console.log(res.next().value);
- console.log(res.previous().value);
- console.log(res.previous().value);
- console.log(res.previous().value);
2
3
2
Please try the above example
here.
Please let me know your feedback and comments.