Created
January 11, 2011 07:17
-
-
Save taiju/774152 to your computer and use it in GitHub Desktop.
クラスメソッド版iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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