Skip to content

Instantly share code, notes, and snippets.

@taiju
Created January 11, 2011 07:17
Show Gist options
  • Save taiju/774152 to your computer and use it in GitHub Desktop.
Save taiju/774152 to your computer and use it in GitHub Desktop.
クラスメソッド版iterator
(function() {
var _Iterator = function() {
var that = this;
return function(items) {
if (!items.length) throw new TypeError(typeof items + ' is not permitted.');
that._items = (items instanceof Array) ? items.slice() : Array.prototype.slice.call(items);
that._limit = that._items.length;
that._item;
return that;
};
};
_Iterator.prototype = {
_move: function(method) {
this._item = this._items[method]();
this._limit--;
if (this._limit === -1) throw new Error('Stop Iteration');
return this;
},
next: function() {
return this._move('shift');
},
prev: function() {
return this._move('pop');
},
get: function(callback) {
if (typeof callback === 'function') {
callback(this._item);
return this;
}
else return this._item;
}
};
window.Iterator = new _Iterator();
})();
Iterator([1,2,3]).next().get(console.log).prev().get(console.log).next().get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment