summaryrefslogtreecommitdiffhomepage
path: root/packages/util/src/binary.ts
diff options
context:
space:
mode:
authorDax <[email protected]>2025-11-21 20:41:27 -0500
committerGitHub <[email protected]>2025-11-21 20:41:27 -0500
commit49408c00e964093c654ee270d545c0e29857e61f (patch)
tree600b2a94cd082c0af221fd84fd5346cfe8f9ace4 /packages/util/src/binary.ts
parent76192fbcedff945b5d529a5d733deb2488ee9c8a (diff)
downloadopencode-49408c00e964093c654ee270d545c0e29857e61f.tar.gz
opencode-49408c00e964093c654ee270d545c0e29857e61f.zip
enterprise (#4617)
Co-authored-by: GitHub Action <[email protected]> Co-authored-by: Adam <[email protected]>
Diffstat (limited to 'packages/util/src/binary.ts')
-rw-r--r--packages/util/src/binary.ts41
1 files changed, 41 insertions, 0 deletions
diff --git a/packages/util/src/binary.ts b/packages/util/src/binary.ts
new file mode 100644
index 000000000..3d8f61851
--- /dev/null
+++ b/packages/util/src/binary.ts
@@ -0,0 +1,41 @@
+export namespace Binary {
+ export function search<T>(array: 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 }
+ }
+
+ export function insert<T>(array: T[], item: T, compare: (item: T) => string): T[] {
+ const id = compare(item)
+ let left = 0
+ let right = array.length
+
+ while (left < right) {
+ const mid = Math.floor((left + right) / 2)
+ const midId = compare(array[mid])
+
+ if (midId < id) {
+ left = mid + 1
+ } else {
+ right = mid
+ }
+ }
+
+ array.splice(left, 0, item)
+ return array
+ }
+}