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.
Sagar Pandurang KapPosted Jan 21, 2018, 11:37 PM
Nice yaar .Easy one...