@contextjs/collections
Version:
Strongly-typed collection classes for TypeScript, including List, Dictionary, Queue, Stack, and HashSet.
26 lines (25 loc) • 915 B
JavaScript
export class BinarySearch {
static search(items, target, compare) {
let low = 0;
let high = items.length - 1;
const defaultCompare = (a, b) => {
if (typeof a === 'number' && typeof b === 'number')
return a - b;
if (typeof a === 'string' && typeof b === 'string')
return a.localeCompare(b);
throw new Error("Unsupported default comparison type. Use a custom compare function.");
};
const comparison = compare || defaultCompare;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const comparisonResult = comparison(items[mid], target);
if (comparisonResult === 0)
return mid;
if (comparisonResult < 0)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}