Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Created August 31, 2021 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dSalieri/87d36e71cdccb3c90795794d268c9481 to your computer and use it in GitHub Desktop.
Save dSalieri/87d36e71cdccb3c90795794d268c9481 to your computer and use it in GitHub Desktop.
Finds closest value in sorted array
function closestPoint(arr, point){
if(!Array.isArray(arr)) return [];
point = Number.isFinite(point) ? point : 0;
let prevDiff = Infinity;
let result = arr.findIndex((value,key) => {
let diff = Math.abs(value - point);
return diff >= prevDiff ? true : (prevDiff = diff, false);
});
result = result === -1 ? arr.length - 1 : result - 1;
return {key: result, value: arr[result]};
}
/// Examples of usage
closestPoint([10,20,30,40,50,60,70,80,90,100]) /// expected: {key:0, value:10}
closestPoint([10,20,30,40,50,60,70,80,90,100],50) /// expected: {key:4, value:50}
closestPoint([10,20,30,40,50,60,70,80,90,100],-1000) /// expected: {key:0, value:10}
closestPoint([10,20,30,40,50,60,70,80,90,100],1000) /// expected: {key:9, value:100}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment