Binary Search Variant With Lower Bound (TypeScript)
Find the leftmost position where a sorted array can accept a target using a typed binary search lower bound variant.
Code
function lowerBound<T>(arr: T[], target: T, cmp: (a: T, b: T) => number): number {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (cmp(arr[mid], target) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
const arr = [1, 2, 2, 3, 4, 6];
console.log(lowerBound(arr, 2, (a, b) => a - b));Output
Captured from a sandboxed run of this snippet in the build pipeline.
1How the snippet works
Binary Search Variant With Lower Bound (TypeScript) reduces to the functions mid and lowerBound.
Iteration happens inside while (lo < hi) — everything outside it runs once.
Applying it
The main signature reads const mid = (lo + hi)
Statements that matter
function lowerBound<T>(arr: T[], target: T, cmp: (a: T, b: T) => number): number {
let lo = 0, hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (cmp(arr[mid], target) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
Interactive Tools for This Topic
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `mid`, `lowerBound` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.