A generic binary search implementation.
deno add jsr:@alg/bisect
import {bisect} from "@alg/sequences";
const arr = [-1, 2, 2, 4, 5];
console.log(bisect(arr, -2)); // 0
console.log(bisect(arr, 2)); // 1
console.log(bisect(arr, 3)); // 3
console.log(bisect(arr, 6)); // 5
A function defining the <
relation can be given to define the ordering of
items.
import {bisect} from "@alg/sequences";
const strings = ["a", "abc", "abcd"];
const lt = (a, b) => a.length < b.length
console.log(bisect(strings, "ab", lt)); // 1