I've ran a few tests, not extensive though, and it apparently works. Like many standard binary search algorithms, if the number returned is < 0, you can take the complement (~) of the returned value to find the insert point, eg const ix = bs(arr, 5); // ~ix is the insertion point
interface bsRange {
min: number;
max: number;
}
const bs = (arr: number[], value: number, range: bsRange | null = null): number => {
if (!range) range = {
min: 0, max: arr.length - 1
};
const indexToCheck = Math.floor((range.min + range.max) / 2);
const iValue = arr[indexToCheck];
if (value === iValue) return indexToCheck;
if (range.max === range.min) {
// we're at the last element to check
if (iValue > value) {
return ~(range.max);
} else {
return ~(range.max) - 1;
}
}
if (value < iValue) {
range.max = indexToCheck - 1;
} else if (value > iValue) {
range.min = indexToCheck + 1;
}
return bs(arr, value, range);
};
```