Created
October 10, 2011 11:13
-
-
Save trekdemo/1275069 to your computer and use it in GitHub Desktop.
Min/Max selection in javascript ( ruby style )
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
// Usage | |
// [1, 2, 3, 4].max() => 4 | |
// [1, 2, 3, 4].min() => 1 | |
// | |
// With blocks | |
// [1, 2, 3, 4].max( function(d){ | |
// return d*-1; | |
// }); => -1 | |
// | |
// [1, 2, 3, 4].min( function(d){ | |
// return d*-1; | |
// }); => -4 | |
if( Array.prototype.max === undefined ) { | |
Array.prototype.max = function(block) { | |
if( block === undefined || typeof(block) !== "function" ){ | |
block = function( e ){ return e; }; | |
} | |
var max = block( this[0] ); | |
var len = this.length; | |
for (var i = 1; i < len; i++) if (block( this[i] ) > max) max = block( this[i] ); | |
return max; | |
} | |
} | |
if( Array.prototype.min === undefined ) { | |
Array.prototype.min = function(block) { | |
var min = block( this[0] ); | |
var len = this.length; | |
for (var i = 1; i < len; i++) if (block( this[i] ) < min) min = block( this[i] ); | |
return min; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment