/ Published in: JavaScript

Released into the public domain by Josh Atkins, 2017. Can't see any bugs in this. Of course, you could use binary search if you wanted.
Expand |
Embed | Plain Text
function nearestK(k, haystack) { var smallestDistance = Infinity, distance, closest; for (var i = 0, length = haystack.length; i < length; i++) { distance = Math.abs(haystack[i] - k); if (distance <= smallestDistance) { smallestDistance = distance; closest = haystack[i]; } if (haystack[i] > k) { break; } } return closest; }
You need to login to post a comment.