Created
February 2, 2015 22:53
-
-
Save wende/abef19d53b53a2b9bffa to your computer and use it in GitHub Desktop.
This file contains 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
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