-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-1.js
63 lines (50 loc) · 1004 Bytes
/
5-1.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
const map = {};
const values = [];
const MAX = 3;
function removeOldest() {
let oldestKey = values.pop();
delete map[oldestKey];
}
function insert(key) {
values.unshift(key);
}
function isFull() {
return values.length === MAX;
}
function set(key, value) {
if (map[key]) {
// Already in cache
return;
}
if (isFull()) {
removeOldest();
}
insert(key);
map[key] = value;
}
function get(key) {
let value = map[key];
return value ? value : null;
}
function testSet(key, value) {
console.log(`SET ${key}: ${value}`)
set(key, value);
}
function testGet(...keys) {
keys.forEach(key => {
let value = get(key);
console.log(`GET ${key}: ${value}`);
});
console.log('\n');
}
testSet('a', 1);
testGet('a');
testSet('b', 2);
testGet('a', 'b');
testSet('c', 3);
testSet('c', 3);
testGet('a', 'b', 'c');
testSet('d', 4);
testGet('a', 'b', 'c', 'd');
testSet('e', 5);
testGet('a', 'b', 'c', 'd', 'e');