Reputation: 165
I have a list of coordinates
const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];
And I am wondering is there a way to calculate bounding box width and height having only these coordinates?
Upvotes: 3
Views: 9480
Reputation: 15530
I guess, that would be the difference between minimum and maximum values of x
(width) and y
(height).
While the obvious way to calculate those may seem to be using of Math.max()
/Math.min()
over extracted arrays of coordinates, it requires looping source array several times unnecessarily, whereas single pass (e.g. with Array.prototype.reduce()
) is quite enough and may perform noticeably faster, when input array is relatively large:
const points = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}],
{width, height} = points.reduce((acc, {x,y}) => {
if(!acc.mX || x < acc.mX){
acc.mX = x
} else if (!acc.MX || x > acc.MX){
acc.MX = x
}
if(!acc.mY || y < acc.mY){
acc.mY = y
} else if (!acc.MY || y > acc.MY){
acc.MY = y
}
acc.width = acc.MX - acc.mX
acc.height = acc.MY - acc.mY
return acc
}, {width: 0, height: 0})
console.log(`width: ${width}; height: ${height}`)
Upvotes: 4
Reputation: 4451
Using the map()
function transform the input array into array of x
or y
values. You can then feed these transformed arrays to Math.min()
and Math.max()
to get left
, right
, bottom
and top
to compute the bounding box
. When you have the bounding box
, the width and height calculation is straight forward (subtract min from max). See code snippet below.
const coords = [{x:10, y:20}, {x:5, y:6}, {x:1, y:25}, {x:11, y:2}];
const xArr = coords.map(c => c.x);
const yArr = coords.map(c => c.y);
const l = Math.min(...xArr);
const r = Math.max(...xArr);
const b = Math.min(...yArr);
const t = Math.max(...yArr);
const width = r - l;
const height = t - b;
console.log(width, height);
Upvotes: 6
Reputation: 1121
Have a look at this snippet. Guess this is an approach to start with.
Some explanations:
We're calculating the minX, maxX, minY and maxY values from the coords set using Math.operationMinOrMax(...coords.map(c => c.propertyXorY))
.
Size (property w and h) can be calulated by substracting maxX - minX
and maxY - minY
.
const boundingBox = (coords) => {
const minX = Math.min(...coords.map(c => c.x)), maxX = Math.max(...coords.map(c => c.x));
const minY = Math.min(...coords.map(c => c.y)), maxY = Math.max(...coords.map(c => c.y));
return {
x: minX,
y: minY,
w: maxX - minX,
h: maxY - minY
}
}
console.log(
boundingBox( [ {x:10,y:5}, {x:100,y:0}, {x:100,y:100}, {x:12,y:50}, {x:0,y:100}, {x:27,y:22} ])
);
Upvotes: 0