-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
38 lines (35 loc) · 1.04 KB
/
index.ts
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
function LRUCache(capacity: number) {
if (capacity < 1) throw Error("capacity invalid");
const map = new Map<number, number>();
function get(key: number): number {
if (map.has(key)) {
const result = map.get(key);
if (typeof result === "number") {
map.delete(key);
map.set(key, result);
return result;
}
}
return -1;
}
function put(key: number, value: number): void {
if (map.has(key)) {
map.delete(key);
map.set(key, value);
} else {
map.set(key, value);
if (map.size > capacity) {
const firstkey = ((map) => {
for (const key of map.keys()) {
return key;
}
throw Error("empty map");
})(map);
map.delete(firstkey);
}
}
}
return { get, put };
}
type LRUCache = ReturnType<typeof LRUCache>;
export default LRUCache;