Iterator
http://robdodson.me/blog/2012/08/10/javascript-design-patterns-iterator/
by MrPolywhirl
JavaScript
var Iterator = function (iterable) {
this.iterable = iterable;
this.i = 0;
this.type = Iterator.inpectType(iterable);
this.keys = this.type === 'Object' ? Object.keys(iterable) : undefined;
this.length = this.type === 'Object' ? this.keys.length : iterable.length;
};
Iterator.prototype.currIndex = function () {
if (this.keys) {
return this.keys[this.i]
} else {
return this.i;
}
};
Iterator.prototype.next = function () {
if (this.keys) {
var element = this.iterable[this.keys[this.i]];
this.i++;
return element;
} else {
return this.iterable[this.i++];
}
};
Iterator.prototype.hasNext = function () {
return this.i < this.length;
};
Iterator.prototype.curr = function () {
if (this.keys) {
return this.iterable[this.keys[this.index]];
} else {
return this.iterable[this.i];
}
};
Iterator.prototype.reset = function () {
this.i = 0;
};
Iterator.inpectType = function (iterable) {
return Object.prototype.toString.call(iterable).slice(8, -1);
};
var iterators = [
[1, 2, 3, 4, 5], {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five'
}]
var it1 = new Iterator(iterators);
while (it1.hasNext()) {
var it2 = new Iterator(it1.next());
console.log('BEGIN:', it2.type);
while (it2.hasNext()) {
console.log(it2.next());
}
}