When searching, this code will find the closest match. Usually, the closest match's x value is smaller than the target.x.
Is there a way to find the closest match where match.x is greater than or equal to the target.x value and match.y is the nearest y value?
The data is organized in ascending order based on x and then y.
var data = [
{"x": 750, "y": 750},
{"x": 750, "y": 850},
{"x": 1000, "y": 500},
{"x": 1000, "y": 1000},
{"x": 2000, "y": 2000},
{"x": 3000,"y": 3000}
];
console.log("Test 800", findClosestMatchGreaterOrEqual({'x': 800,'y': 800}));
// TEST 800 {x: 750, y: 850}
console.log("Test 2300", findClosestMatchGreaterOrEqual({'x': 2300,'y': 2300}));
// TEST 2300 {x: 2000, y: 2000}
function findClosestMatchGreaterOrEqual(target) {
var low = 0;
var high = data.length - 1;
var item = null;
var lastItem = null;
while (low <= high) {
var mid = ((low + high) / 2) | 0;
lastItem = item;
item = data[mid];
var compare = compareItems(item, target);
if (compare > 0) high = mid - 1;
else if (compare < 0) low = mid + 1;
else return item;
}
if (Math.abs(lastItem.x - target.x) < Math.abs(item.x - target.x)) return lastItem;
return item;
}
function compareItems(a, b) {
if (a.x != b.x) return a.x - b.x;
if (a.y != b.y) return a.y - b.y;
return 0;
}