Skip to content

Instantly share code, notes, and snippets.

@trekdemo
Created October 10, 2011 11:13
Show Gist options
  • Save trekdemo/1275069 to your computer and use it in GitHub Desktop.
Save trekdemo/1275069 to your computer and use it in GitHub Desktop.
Min/Max selection in javascript ( ruby style )
// 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