Given this code:
var minX = minY = maxX = maxY = 0;
for(var i=0; i<objArray.length; i++){
if(objArray[i].x < minX){
minX = objArray[i].x;
}else if(objArray [i].x > maxX){
maxX = objArray[i].x;
}
if(objArray[i].y < minY){
minY = objArray[i].y;
}else if(objArray [i].y > maxY){
maxY = objArray[i].y;
}
}
It works, but I don't think it is very elegant. It is simple logic, but it uses 10 lines of code. Can it be improved?
You could use Math.min and Math.max:
var minX = minY = Number.POSITIVE_INFINITY,
maxX = maxY = Number.NEGATIVE_INFINITY;
for(var i=0; i<objArray.length; i++){
minX = Math.min(objArray[i].x, minX);
minY = Math.min(objArray[i].y, minY);
maxX = Math.max(objArray[i].x, maxX);
maxY = Math.max(objArray[i].y, maxY);
}
For loop speed optimization you could store the length to only calculate it once:
for(var i=0, len = objArray.length; i<len; i++){
//...
}
Check this article for more information about loop optimization.
Another approach, just for "functional fun", since I wouldn't recommend it for performance, could be to separate the x and y values to two arrays using Array.map, and then call the min and max functions with apply:
var allX = objArray.map(function (o) { return o.x; });
var allY = objArray.map(function (o) { return o.y; });
minX = Math.min.apply(Math, allX);
minY = Math.min.apply(Math, allY);
maxX = Math.max.apply(Math, allX);
maxY = Math.max.apply(Math, allY);
How this works?
The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)
So if we call:
Math.min.apply(Math, [1,2,3,4]);
The apply function will execute:
Math.min(1,2,3,4);
Note that the first parameter, the context, is not important for these functions since they are static, they will work regardless of what is passed as the context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With