Iterator Pattern (aka Custom Iterators)
JS
S
JavaScriptIt's basically an object that KNOWS how to access items from a collection and if the iteration is finished or not. It's API consists on a next() method that returns the next item
1function createIterator(array) {
2 let nextIndex = 0;
3 return {
4 next: function(){
5 return nextIndex < array.length ?
6 { value: array[nextIndex++], done: false } :
7 { done: true}
8 }
9 }
10}
11
12const myIt = createIterator(['code','recipes']);
13console.log(myIt.next().value);
14console.log(myIt.next().value);
15console.log(myIt.next().done);Created on 2/28/2018