1//Iterators
2function fruitsIterator(array) {
3 let nextIndex = 0;
4 //fruitsIterator will return an object
5 return {
6 next: function () {
7 if (nextIndex < array.length) {
8 //next function will return the below object
9 return {
10 value: array[nextIndex++],
11 done: false,
12 };
13 } else {
14 return { done: true };
15 }
16 },
17 };
18}
19let myArr = ["apple", "banana", "orange", "grapes"];
20console.log("My array is", myArr);
21
22//using the iterator
23const fruits=fruitsIterator(myArr);
24console.log(fruits.next()); //apple
25console.log(fruits.next());//banana
26console.log(fruits.next());//grapes
27