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:
For loop speed optimization you could store the length to only calculate it once:
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:
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:
The apply function will execute:
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.