Skip to content

Instantly share code, notes, and snippets.

@RinniSwift
Last active January 21, 2021 01:20
Show Gist options
  • Save RinniSwift/644e30afd8a577469f51cc1a2398497f to your computer and use it in GitHub Desktop.
Save RinniSwift/644e30afd8a577469f51cc1a2398497f to your computer and use it in GitHub Desktop.
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