Created
May 16, 2012 10:14
-
-
Save WebReflection/2709261 to your computer and use it in GitHub Desktop.
A way to use some returning the very first matched object
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
| // @license WTFPL | |
| Array.prototype.search = function (some) { | |
| return function search(cb, ctx) { | |
| var result = {f:cb, c:ctx, r:result}; | |
| this.some(some, result); | |
| return result.r; | |
| }; | |
| }(function some(v, i, self) { | |
| if (this.f.call(this.c, v, i, self)) { | |
| this.r = v; | |
| return !0; | |
| } | |
| }); | |
| // @example | |
| var o = [1,2,3].search(function (v) { | |
| return v < 4; | |
| }); | |
| if (o !== undefined) { | |
| // do stuff | |
| // o === 1 in this case | |
| } |
Author
to simply have same Array#extras signature, rely in the native or properly shimmed "in" check for indexes, and let native/shimmed version handle properly the error ... I prefer to trust native browsers speed and implementation in this case but surely if performances are a must I would use your version without polluting the Array.prototype at all :-)
Oh, now I got it :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe I missing something here, but why not: