Created
November 5, 2011 23:08
-
-
Save bga/1342153 to your computer and use it in GitHub Desktop.
breakable generic _each.js
This file contains hidden or 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
| /* | |
| Generic breakable _each | |
| */ | |
| Object.prototype._each = function(_fn) { | |
| for(var i in this) { | |
| if(!{}.hasOwnProperty.call(this, i)) | |
| continue | |
| var ret = _fn(this[i], i, this) | |
| if(ret != null) | |
| return ret | |
| } | |
| } | |
| // defaultly {Object#_each} enumarates own keys but you can use {Object#_eachNonOwn} | |
| Object.prototype._eachNonOwn = function(_fn) { | |
| for(var i in this) { | |
| var ret = _fn(this[i], i, this) | |
| if(ret != null) | |
| return ret | |
| } | |
| } | |
| Array.prototype._each = function(_fn) { | |
| for(var i = 0; i < this.length; ++i) { | |
| if(!{}.hasOwnProperty.call(this, i)) // Array can be holed | |
| continue | |
| var ret = _fn(this[i], i, this) | |
| if(ret != null) | |
| return ret | |
| } | |
| } | |
| // You can implement any ccollection's method using _each | |
| // For example {_map} | |
| Object.prototype._map = function(_fn) { | |
| var dest = Object.create(Object.getPrototypeOf(this)) | |
| this._each(function(v, k, self){ dest[k] = _fn(v, k, self) }) | |
| return dest | |
| } | |
| // or {_find} | |
| Object.prototype._find = function(_fn) { | |
| return this._each(function(v, k, self){ if(_fn(v, k, self)) return k }) | |
| } | |
| // Numeric range which acts as collection | |
| var Range = function(begin, end, step) { | |
| this.begin = begin | |
| this.end = end | |
| this.step = step | |
| } | |
| Range.prototype._each = function(_fn) { | |
| for(var i = this.begin; i < this.end; i += this.step) | |
| { | |
| var ret = _fn(i, i, this) | |
| if(ret != null) | |
| return ret | |
| } | |
| } | |
| // But it can acts as ordinary loop | |
| // loop w/ ordinary 'break' | |
| a._each(function(v, k){ | |
| if(v == 1) | |
| return | |
| }) | |
| // loop /w continue | |
| var Continue = function(){} | |
| var _continue = function(){ throw new Continue() } | |
| var _fContinue = function(_fn) { | |
| return function(){ | |
| try { | |
| return _fn.apply(this, arguments) | |
| } catch(err) { | |
| if(err instanceof Continue) | |
| // do nothing | |
| else | |
| throw err | |
| } | |
| } | |
| } | |
| a._each(_fContinue(function(v, k){ | |
| if(v == 1) | |
| _continue() | |
| })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment