Skip to content

Instantly share code, notes, and snippets.

@qingwei91
Last active September 6, 2017 11:05
Show Gist options
  • Save qingwei91/70ca423992940ca7de46e490eb846596 to your computer and use it in GitHub Desktop.
Save qingwei91/70ca423992940ca7de46e490eb846596 to your computer and use it in GitHub Desktop.
class CacheBackEnd[K, V] {
private var map = Map.empty[K, V] // ignore the fact it is not thread safe
// `compute` is a function, only evaluated in case of cache miss
def getOrElse(k: K, compute: K => V): V = {
map.get(k) match {
case Some(v) => v // cache hit
case None =>
val v = compute(k)
map = map + (k -> v)
v
}
}
}
def cache[K, V](fn: K => V)(cacheStorage: CacheBackEnd[K, V]): K => V = {
(k: K) =>
cacheStorage.getOrElse(k, fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment