I’m using an iterative binary search to help find some stuff, and am wondering if anyone knows of a more expressive way to perform these greater than, equal to or less than statements.
...
while (low <= high && position === -1) {
mid = Math.floor((low + high) / 2);
if (haystack[mid] > needle) {
high = mid - 1;
} else if (haystack[mid] < needle) {
low = mid + 1;
} else {
position = mid;
}
}
If we use (haystack[mid] - needle) we can then end up with a condition that’s either positive, equal to, or negative; but other than going recursive on things, are there more expressive ways to make use of this kind of condition other than an if/elseif/else construct?
...
while (low <= high && position === -1) {
mid = Math.floor((low + high) / 2);
diff = haystack[mid] - needle;
position = mid + Math.max(-1, Math.min(diff, 1));
}
Basically I’m taking the difference between haystack[mid] and needle and then clamp it on the open interval (-1, 1) and then add that to position.
End effect is the same as your code, but without (explicit) if/then/else.
Are more readable version:
function clamp(val, min, max) {
return Math.max(min, Math.min(val, max))
}
...
while (low <= high && position === -1) {
mid = Math.floor((low + high) / 2);
diff = haystack[mid] - needle;
position = mid + clamp(diff, -1, 1);
}