Array.prototype.search
This looks very much like sort, a bit more memory efficient though as it doesn't return the whole thing. I like it although Array.prototype is probably not the right place. I heard something about up and coming iterator related functions module?
On Fri, May 25, 2012 at 9:26 PM, Rich Walrath <richwalrath at gmail.com> wrote:
Hello,
I've been playing around with an iterative array method I wrote earlier today. I thought it would be a good idea to post it here and see wher
The idea behind this method is to search for the best match. It does this by allowing you to specify a weighing function that calculates the best result based by comparing two of the values at a time.
This is pretty trivially done with reduce. Just modify your function very slightly:
arr.reduce(function(a,b) { return a.x > b.x ? a : b; });
Same efficiency as your iterative method.
Hello,
I've been playing around with an iterative array method I wrote earlier today. I thought it would be a good idea to post it here and see wher
The idea behind this method is to search for the best match. It does this by allowing you to specify a weighing function that calculates the best result based by comparing two of the values at a time.
Here is a variant to the method I have been toying with:
Array.prototype.search = function( searchFn, scope ){ var len = this.length, i = 1, curr;
if(len === 0){ throw new TypeError("Length is 0 and no results are possible."); }
curr = this[0];
for( ; i < len; i++ ) { if( i in this && searchFn.call( scope, curr, this[i], i, this ) ) { curr = this[i]; } }
return curr; };
For an example say you have a list of coordinates and you want to get the largest x coordinate you would just do something like this:
var arr = [ { x: 0, y: 124 }, { x: 50, y: 34 }, { x: -23, y: 85 }, { x: 163, y: 40 }, { x: 65, y: -20 } ];
arr.search( function(c,v,i,o){ return v.x > c.x; });
The end result would be the { x: 163, y: 40 } object because it has the largest x value, which is what we were looking for.
Rich Walrath