You can apply some 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 use the iterator to iterate over the list and save the state of the last iteration over the 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);
source share