Introduction
- 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();
- }
Output
1
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);
Output
1
2
3
2
1
index out of range
Please try the above example here.
Please let me know your feedback and comments.
Sagar Pandurang KapPosted Jan 21, 2018, 11:37 PM
Nice yaar .Easy one...