Reputation:
I am wondering what is the best possible algorithm in JS for a min() function with two or more arguments ?
NOTE: it should work on any JS types that can be compared with ">" or "<" operators. For example:
min( new Date(1959,6,3), new Date(1960,7,8), new Date(1925,6,9));
/*
should return: Thu Jul 9 00:00:00 UTC+0200 1925
*/
Thus Math.min and Math.max might not be the good candidates.
Thanks ...
EDIT: I am thinking along these lines:
"use strict" ;
var d1 = new Date(1959,6,3), d2 = new Date(1960,7,8), d3 = new Date(1925,6,9) ;
function min (a,b)
{
if ( arguments.length > 2 ) {
var args = Array.prototype.slice.call(arguments,0) ;
args.shift() ;
args[0] = min(a,b) ;
return min.apply( this, args ) ;
}
else {
return a > b ? b : a ;
}
}
min(d1,d2,d3);
/*
returns: Thu Jul 9 00:00:00 UTC+0200 1925
*/
Above can be optimized, but it works for 2 or more numbers and strings too. Of course inside JS intrinsic comparators rules.
Upvotes: 0
Views: 149
Reputation:
Perhaps this is the optimal solution:
"use strict"
var arr = create_array_of_any_scalar_type_for_testing();
var min = arr.reduce(function(a, b) {return a < b ? a : b ; });
I also dare to think, on all modern browsers this will be the fastest solution, too. The complete packaged solution might be this:
"use strict" ;
function min (a,b)
{
if ( arguments.length > 2 ) {
var args = Array.prototype.slice.call(arguments,0) ;
return args.reduce(function(a, b) {return a < b ? a : b ; });
}
else {
return a > b ? b : a ;
}
}
/* quick test with dates */
var d1 = new Date(1959,6,3), d2 = new Date(1960,7,8), d3 = new Date(1925,6,9) ;
min(d1,d2,d3);
/*
returns: Thu Jul 9 00:00:00 UTC+0200 1925
*/
Enjoy .
Upvotes: 0
Reputation: 1629
watch this fiddle:
function min(/*...args...*/){
var len = arguments.length;
if(len < 1)
return null;
var lowest = arguments[0];
for(var i = 0; i < len; i++){
if(arguments[i] < lowest)
lowest = arguments[i];
}
return lowest;
}
the only thing is (and you should change it as needed) is that if no arguments are passed it will return NULL
. THe Function can take as much arguments as you want.
Upvotes: 2
Reputation: 3491
i think the Min()
is ok
From W3schools :
Return the number with the lowest value:
var a=Math.min(5,10);
var b=Math.min(0,150,30,20,38);
var c=Math.min(-5,10);
var d=Math.min(-5,-10);
var e=Math.min(1.5,2.5);
The result of a,b,c,d, and e will be:
5
0
-5
-10
1.5
Upvotes: 1