Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created May 16, 2012 10:14
Show Gist options
  • Select an option

  • Save WebReflection/2709261 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/2709261 to your computer and use it in GitHub Desktop.
A way to use some returning the very first matched object
// @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
}
@kentaromiura
Copy link

Maybe I missing something here, but why not:

Array.prototype.search = function(test, context){
    var me = this;
    for(var i=0, max=me.length; i<max; i++){
        if(test.call(context||this, me[i])) return me[i];
    }
}

@WebReflection
Copy link
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 :-)

@kentaromiura
Copy link

Oh, now I got it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment