-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0981-time-based-key-value-store.js
More file actions
47 lines (41 loc) · 1.18 KB
/
0981-time-based-key-value-store.js
File metadata and controls
47 lines (41 loc) · 1.18 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
/**
* Time Based Key Value Store
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
class TimeMap {
constructor() {
this.dataStorage = new Map();
}
set(identifierKey, storedValue, requestTime) {
let timestampedRecords = this.dataStorage.get(identifierKey);
if (!timestampedRecords) {
timestampedRecords = [];
this.dataStorage.set(identifierKey, timestampedRecords);
}
timestampedRecords.push([requestTime, storedValue]);
}
get(identifierKey, requestTime) {
const timeValueList = this.dataStorage.get(identifierKey);
if (!timeValueList || timeValueList.length === 0) {
return "";
}
let searchStart = 0;
let searchEnd = timeValueList.length;
while (searchStart < searchEnd) {
const centralPoint = Math.floor((searchStart + searchEnd) / 2);
const [currentPointTime, currentPointValue] = timeValueList[centralPoint];
if (currentPointTime > requestTime) {
searchEnd = centralPoint;
} else {
searchStart = centralPoint + 1;
}
}
if (searchStart === 0) {
return "";
} else {
const finalIndex = searchStart - 1;
return timeValueList[finalIndex][1];
}
}
}