JSFiddle - React, Tailwind, and code Playground
by ruisoftware
JavaScript
var pnts = [[6,14], [7,13], [8,12], [5,8], [10,7], [8,6.5], [7,5], [6,4], [3,2]],
center = [7,6],
sortedX = [],
sortedY = [],
findPnt = function(findX, elem, inPntsArray) {
var from = 0,
to = inPntsArray.length - 1,
middle = 0;
while (from <= to) {
middle = Math.floor((to - from + 1)/ 2);
var middleValue = inPntsArray[middle][findX? 0:1];
if (middleValue < elem) {
console.log(from + ' ' + middle + ' ' + to + ' right');
from = middle + 1;
} else {
if (middleValue > elem) {
console.log(from + ' ' + middle + ' ' + to + ' left');
to = middle - 1;
} else {
console.log(from + ' ' + middle + ' ' + to + ' found');
return {found: true, idx: middle};
}
}
}
return {found: false, idx: middle};
},
findX = function(x) {
return findPnt(true, x, sortedX);
};
findY = function(y) {
return findPnt(false, y, sortedY);
},
insertSorted = function(isX, pntsIndex) {
var findResult = isX? findX(pnts[pntsIndex]) : findY(pnts[pntsIndex]);
(isX? sortedX : sortedY).splice(findResult.idx, 0, pntsIndex);
},
sortX = function () {
for (idx in pnts) {
insertSorted(true, idx);
}
};
console.log('raw points');
for (idx in pnts) {
console.log(pnts[idx]);
}
console.log('sortedX points');
for (idx in pnts) {
console.log(sortedX[idx]);
}
console.log('sortedY points');
for (idx in pnts) {
console.log(sortedY[idx]);
}
//console.log(findX(5));