Skip to content

Instantly share code, notes, and snippets.

@kabirnayeem99
Created August 2, 2024 18:51
Show Gist options
  • Save kabirnayeem99/5830b6161dab1a90eab99ac439953dc4 to your computer and use it in GitHub Desktop.
Save kabirnayeem99/5830b6161dab1a90eab99ac439953dc4 to your computer and use it in GitHub Desktop.
LRU Cache Kotlin Multiplatform
public inline fun <K, V> lruCacheOf(capacity: Int): LRUCache<K, V> = LRUCache(capacity = capacity)
class LRUCache<K, V>(private val capacity: Int) {
private val cache = LinkedHashMap<K, V>(initialCapacity = capacity, loadFactor = 0.75F)
fun get(key: K): V? {
if (!containsKey(key)) return null
val value = remove(key)!!
cache[key] = value
return value
}
fun clear() = cache.clear()
fun remove(key: K) = cache.remove(key)
fun put(key: K, value: V) {
if (cache.containsKey(key)) {
cache.remove(key)
} else if (cache.size == capacity) {
cache.remove(cache.keys.first())
}
cache[key] = value
}
val size: Int
get() = cache.size
fun isEmpty() = cache.isEmpty()
fun containsKey(key: K) = cache.containsKey(key)
fun containsValue(value: V) = cache.containsValue(value)
fun putAll(from: Map<out K, V>) = cache.putAll(from)
val keys: MutableSet<K>
get() = cache.keys
val values: MutableCollection<V>
get() = cache.values
val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() = cache.entries
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment