forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_utils.js
70 lines (60 loc) · 1.18 KB
/
_utils.js
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
export function sort (a, b, hashCode) {
// Short-circuit comparison if a and b are strictly equal
// This is absolutely necessary for indexed objects that
// don't have the idAttribute field
if (a === b) {
return 0
}
if (hashCode) {
a = hashCode(a)
b = hashCode(b)
}
if ((a === null && b === null) || (a === undefined && b === undefined)) {
return -1
}
if (a === null || a === undefined) {
return -1
}
if (b === null || b === undefined) {
return 1
}
if (a < b) {
return -1
}
if (a > b) {
return 1
}
return 0
}
export function insertAt (array, index, value) {
array.splice(index, 0, value)
return array
}
export function removeAt (array, index) {
array.splice(index, 1)
return array
}
export function binarySearch (array, value, field) {
let lo = 0
let hi = array.length
let compared
let mid
while (lo < hi) {
mid = ((lo + hi) / 2) | 0
compared = sort(value, array[mid], field)
if (compared === 0) {
return {
found: true,
index: mid
}
} else if (compared < 0) {
hi = mid
} else {
lo = mid + 1
}
}
return {
found: false,
index: hi
}
}