Created
May 12, 2019 09:02
-
-
Save achernoprudov/a2a86936228d7bf3ed69288a8a6732d0 to your computer and use it in GitHub Desktop.
LRU Cache implementation. Swift version.
This file contains hidden or 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<K: Hashable, V> { | |
private class Entity<V> { | |
let value: V | |
let key: K | |
var left: Entity<V>? | |
var right: Entity<V>? | |
init(value: V, key: K) { | |
self.value = value | |
self.key = key | |
} | |
} | |
let maxSize: Int | |
private var map: [K : Entity<V>] = [:] | |
private var head, tail: Entity<V>? | |
init(maxSize: Int) { | |
self.maxSize = maxSize | |
} | |
func put(_ value: V, forKey key: K) { | |
if let oldEntity = map[key] { | |
remove(oldEntity) | |
} | |
let newEntity = Entity(value: value, key: key) | |
addOnTop(newEntity) | |
if map.count > maxSize { | |
remove(tail!) | |
} | |
} | |
func get(byKey key: K) -> V? { | |
guard let entity = map[key] else { | |
return nil | |
} | |
remove(entity) | |
addOnTop(entity) | |
return entity.value | |
} | |
private func addOnTop(_ entity: Entity<V>) { | |
entity.left = nil | |
entity.right = head | |
head?.left = entity | |
head = entity | |
if tail == nil { | |
tail = entity | |
} | |
map[entity.key] = entity | |
} | |
private func remove(_ entity: Entity<V>) { | |
entity.left?.right = entity.right | |
entity.right?.left = entity.left | |
if entity === head { | |
head = entity.right | |
} | |
if entity === tail { | |
tail = entity.left | |
} | |
entity.left = nil | |
entity.right = nil | |
map[entity.key] = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment