forked from InteraactionGroup/olpapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdicho.js
More file actions
60 lines (59 loc) · 1.39 KB
/
dicho.js
File metadata and controls
60 lines (59 loc) · 1.39 KB
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
class Dichotomous {
constructor(obj) {
if (obj !== undefined) {
this.keys = Object.keys(obj);
this.keys.sort();
this.values = new Array(this.keys.length);
for (let i in this.keys) {
let key = this.keys[i];
this.values[i] = obj[key];
}
} else {
this.keys = [];
this.values = [];
}
}
_dichotomy(key) {
let start = 0;
let end = this.keys.length;
if (end != 0) {
while (true) {
let length = end - start;
let idx = start + (length >> 1);
let k = this.keys[idx];
/**/ if (k < key) start = idx;
else if (k > key) end = idx;
else return [true, idx];
if (length == 1) break;
}
}
return [false, start];
}
set(key, value) {
let [found, idx] = this._dichotomy(key);
while (idx < this.keys.length && this.keys[idx] < key) idx++;
let delCount = found ? 1 : 0;
this.keys.splice(idx, delCount, key);
this.values.splice(idx, delCount, value);
}
del(key) {
let [found, idx] = this._dichotomy(key);
let delCount = found ? 1 : 0;
this.keys.splice(idx, delCount);
this.values.splice(idx, delCount);
}
get(key) {
let [found, idx] = this._dichotomy(key);
return found ? this.values[idx] : undefined;
}
getRange(start, length) {
return {
keys: this.keys.slice(start, start + length),
values: this.values.slice(start, start + length),
};
}
find(key) {
return this._dichotomy(key)[1];
}
}
module.exports = { Dichotomous };