To incorporate the iterator design pattern, you can create a custom Iterator object with functions to iterate over a list and maintain the state of the last iteration.
var CustomIterator = function (list, position) {
return {
hasNext: function () {
return position + 1 < list.length;
},
isDefined: function () {
return (position < list.length && position >= 0);
},
getElement: function () {
return list[position];
},
getPosition: function () {
return position;
},
moveNext: function () {
if (this.hasNext()) { return CustomIterator(list, position + 1); }
return CustomIterator([], 0);
}
}
CustomIterator.forEach = function (action, iterator, length) {
var counter = 0;
while (counter < length && iterator.isDefined()) {
counter++;
action(iterator.getElement(), iterator.getPosition());
iterator = iterator.moveNext();
}
return iterator;
}
Create an instance of the CustomIterator to traverse through the list and store the last iteration state.
var list = [2, 4, 6, 8, 10];
var customIterator = CustomIterator(list, 0);
customIterator = CustomIterator.forEach(function (element, index) {
console.log(element, index);
}, customIterator, 3);
//2 0
//4 1
//6 2
CustomIterator.forEach(function (element, index) {
console.log(element, index);
}, customIterator, 5);
//8 3
//10 4