-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex4.js
More file actions
48 lines (37 loc) · 1.02 KB
/
ex4.js
File metadata and controls
48 lines (37 loc) · 1.02 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
'use strict';
/*
Problem:
Implement `createCache(capacity)` as a bounded LRU cache.
Required API:
- `set(key, value)` stores value.
- `get(key)` returns value or `undefined`.
- `size()` returns current number of items.
- `keys()` returns keys from least-recently-used to most-recently-used.
Rules:
- Capacity is required and must be >= 1.
- On insert over capacity, evict exactly one LRU entry.
- `get` should refresh recency for existing keys.
- Updating existing key should not increase size.
Starter code is intentionally incorrect: unbounded growth, no LRU behavior.
*/
function createCache(capacity) {
if (!Number.isInteger(capacity) || capacity < 1) {
throw new TypeError('capacity must be an integer >= 1');
}
const store = Object.create(null);
return {
set(key, value) {
store[key] = value;
},
get(key) {
return store[key];
},
size() {
return Object.keys(store).length;
},
keys() {
return Object.keys(store);
},
};
}
module.exports = { createCache };