Files
openchamber/packages/ui/src/sync/binary.ts
T

27 lines
624 B
TypeScript
Raw Normal View History

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace Binary {
export function search<T>(
array: readonly T[],
id: string,
compare: (item: T) => string,
): { found: boolean; index: number } {
let left = 0
let right = array.length - 1
while (left <= right) {
const mid = Math.floor((left + right) / 2)
const midId = compare(array[mid])
if (midId === id) {
return { found: true, index: mid }
} else if (midId < id) {
left = mid + 1
} else {
right = mid - 1
}
}
return { found: false, index: left }
}
}