I have an array with alot of items, and I am creating a list of them. I was thinking of paginating the list. I wonder how can I start a forEach
or for
You could apply some kind of implementation of the iterator pattern.
var Iterator = function (list, position) {
return {
isNext: function () {
return position + 1 < list.length;
},
isDefined: function () {
return (position < list.length && position >= 0);
},
element: function () {
return list[position];
},
position: function () {
return position;
},
moveNext: function () {
if (this.isNext()) { return Iterator(list, position + 1); }
return Iterator([], 0);
}
}
Iterator.forEach = function (action, iterator, length) {
var counter = 0;
while (counter < length && iterator.isDefined()) {
counter = counter + 1;
action(iterator.element(), iterator.position());
iterator = iterator.moveNext();
}
return iterator;
}
And then have an iterator to use for going over the list and keep the state of the last iteration over a list.
var list = [1, 3, 5, 3, 6];
var iterator = Iterator(list, 0);
iterator = Iterator.forEach(function (element, index) {
console.log(element, index);
}, iterator, 3);
//1 0
//3 1
//5 2
Iterator.forEach(function (element, index) {
console.log(element, index);
}, iterator, 5);
//3 3
//6 4