Skip to content

Instantly share code, notes, and snippets.

@wende
Created February 2, 2015 22:53
Show Gist options
  • Save wende/abef19d53b53a2b9bffa to your computer and use it in GitHub Desktop.
Save wende/abef19d53b53a2b9bffa to your computer and use it in GitHub Desktop.
object Helpers {
def time[R](block: => R): (R, Long) = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
(result, t1 - t0)
}
}
case class Memoize[-T , +R : ClassTag](duration : Duration, refreshOnGet : Boolean = false)(f: T => R)
(implicit app : Application) extends (T => R) {
val safeCounter = Cache.getAs[Int](Memoize.CACHE_KEY).getOrElse(0)
Cache.set(Memoize.CACHE_KEY, safeCounter + 1)
def apply(x: T) : R = {
val key = safeCounter + x.toString
val result = Cache.getAs[R](key).getOrElse {
val result = f(x)
Cache.set(key, result, duration)
result
}
if(refreshOnGet) Cache.set(key, result, duration)
result
}
}
object Memoize {
implicit def functionToMemoizer[T,R : ClassTag] (f:(T => R)) : Memoizable[T,R] = Memoizable(f)
lazy val CACHE_KEY = "memoize-safe-counter"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment