Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@adiwajshing/keyed-db/lib/BinarySearch.js
1126 views
1
"use strict";
2
Object.defineProperty(exports, "__esModule", { value: true });
3
/**
4
* Binary search
5
* @param array the array to search in
6
* @param predicate return a value of < 0, if the item you're looking for should come before, 0 if it is the item you're looking for
7
*/
8
function binarySearch(array, predicate) {
9
let low = 0;
10
let high = array.length;
11
// base cases to allow entering a sorted collection in O(N)
12
if (array.length === 0)
13
return low;
14
if (predicate(array[low]) < 0)
15
return low - 1;
16
else if (predicate(array[low]) === 0)
17
return low;
18
const maxPred = predicate(array[high - 1]);
19
if (maxPred > 0)
20
return high;
21
else if (maxPred === 0)
22
return high - 1;
23
while (low !== high) {
24
const mid = low + Math.floor((high - low) / 2);
25
const pred = predicate(array[mid]);
26
if (pred < 0)
27
high = mid;
28
else if (pred > 0)
29
low = mid + 1;
30
else
31
return mid;
32
}
33
return low;
34
}
35
exports.default = binarySearch;
36
37