-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
binary-search-bounds.ts
106 lines (95 loc) · 2.88 KB
/
binary-search-bounds.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* Everything in this file was copied and adapted from
* @link https://github.com/mikolalysenko/binary-search-bounds
*
* TODO We should use the original npm module instead when this bug is fixed:
* @link https://github.com/mikolalysenko/binary-search-bounds/pull/14
*/
type Compare<T> = ((a: T, b: T) => number | null | undefined);
function ge<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any): number {
let i: number = h + 1;
while (l <= h) {
const m = (l + h) >>> 1;
const x: any = a[m];
const p: any = (c !== undefined) ? c(x, y) : (x - (y as any));
if (p >= 0) {
i = m; h = m - 1;
} else {
l = m + 1;
}
}
return i;
}
function gt<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any): number {
let i = h + 1;
while (l <= h) {
const m = (l + h) >>> 1;
const x = a[m];
const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));
if (p > 0) {
i = m; h = m - 1;
} else {
l = m + 1;
}
}
return i;
}
function lt<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any): number {
let i = l - 1;
while (l <= h) {
const m = (l + h) >>> 1, x = a[m];
const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));
if (p < 0) {
i = m; l = m + 1;
} else {
h = m - 1;
}
}
return i;
}
function le<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any): number {
let i = l - 1;
while (l <= h) {
const m = (l + h) >>> 1, x = a[m];
const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));
if (p <= 0) {
i = m; l = m + 1;
} else {
h = m - 1;
}
}
return i;
}
function eq<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any): number {
while (l <= h) {
const m = (l + h) >>> 1, x = a[m];
const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));
if (p === 0) {
return m;
}
if (p <= 0) {
l = m + 1;
} else {
h = m - 1;
}
}
return -1;
}
function norm<T>(a: T[], y: T, c: Compare<T>, l: any, h: any, f: any) {
return f(a, y, c, (l === undefined) ? 0 : l | 0, (h === undefined) ? a.length - 1 : h | 0);
}
export function boundGE<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any) {
return norm(a, y, c, l, h, ge);
}
export function boundGT<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any) {
return norm(a, y, c, l, h, gt);
}
export function boundLT<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any) {
return norm(a, y, c, l, h, lt);
}
export function boundLE<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any) {
return norm(a, y, c, l, h, le);
}
export function boundEQ<T>(a: T[], y: T, c: Compare<T>, l?: any, h?: any) {
return norm(a, y, c, l, h, eq);
}