Last active
January 21, 2021 01:20
-
-
Save RinniSwift/644e30afd8a577469f51cc1a2398497f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LRUCache<T: Hashable, U> { | |
// ... | |
/// Sets the specified value at the specified key in the cache. | |
func setObject(for key: T, value: U) { | |
let element = CachePayload(key: key, value: value) | |
let node = Node(value: element) | |
if let existingNode = dictionary[key] { | |
linkedList.moveToHead(node: existingNode) | |
linkedList.head?.payload.value = value | |
dictionary[key] = node | |
} else { | |
if linkedList.count == capacity { | |
if let leastAccessedKey = linkedList.tail?.payload.key { | |
dictionary[leastAccessedKey] = nil | |
} | |
linkedList.remove() | |
} | |
linkedList.insert(node: node, at: 0) | |
dictionary[key] = node | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment