-
Notifications
You must be signed in to change notification settings - Fork 2
/
LRUCache.swift
74 lines (58 loc) · 1.61 KB
/
LRUCache.swift
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
64
65
66
67
68
69
70
71
72
73
74
//
// LRUCache.swift
// FoundationExt
//
// Created by SuXinDe on 2021/9/27.
//
import Foundation
public class LRUCache<KeyType: Hashable, ValueType>: NSObject {
private let maxSize: Int
private var cache: [KeyType: ValueType] = [:]
private var priority: [KeyType] = []
public init(_ maxSize: Int = 500) {
self.maxSize = maxSize
}
public func get(_ key: KeyType) -> ValueType? {
guard let val = cache[key] else {
return nil
}
remove(key)
insert(key, val)
return val
}
public func set(_ key: KeyType, _ val: ValueType) {
if cache[key] != nil {
remove(key)
} else if priority.count >= maxSize, let keyToRemove = priority.last {
remove(keyToRemove)
}
insert(key, val)
}
public subscript(_ key: KeyType) -> ValueType? {
get {
return get(key)
}
set {
if let value = newValue {
set(key, value)
} else {
remove(key)
}
}
}
public override var description: String {
return "LRUCache<\(KeyType.self):\(ValueType.self)>: { \n\(cache) \n}"
}
}
fileprivate extension LRUCache {
private func remove(_ key: KeyType) {
cache.removeValue(forKey: key)
if let idx = priority.firstIndex(of: key) {
priority.remove(at: idx)
}
}
private func insert(_ key: KeyType, _ val: ValueType) {
cache[key] = val
priority.insert(key, at: 0)
}
}