Created
March 29, 2020 22:34
-
-
Save eoinahern/69b6403c6448a275434f6591b09f64c9 to your computer and use it in GitHub Desktop.
a Memoizer class from the book joy of kotlin
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
import java.util.concurrent.ConcurrentHashMap | |
class Memoizer<T, U> private constructor() { | |
private val map = ConcurrentHashMap<T, U>() | |
private fun callLocalMemoize(block: (T) -> U): (T) -> U = { input -> | |
map.computeIfAbsent(input) { | |
block(it) | |
} | |
} | |
companion object { | |
fun <T, U> memoize(inputFun: (T) -> U): (T) -> U { | |
return Memoizer<T, U>().callLocalMemoize(inputFun) | |
} | |
} | |
} | |
fun main() { | |
val myFun: (Int) -> Int = { x -> | |
Thread.sleep(1000) | |
x | |
} | |
val getNumberFun = Memoizer.memoize(myFun) | |
val timeOne = System.currentTimeMillis() | |
val num1 = getNumberFun(2) | |
val timeTwo = System.currentTimeMillis() | |
println("time1 : ${timeTwo - timeOne} : $num1") | |
val timeThree = System.currentTimeMillis() | |
val num2 = getNumberFun(2) | |
val timeFour = System.currentTimeMillis() | |
println("time2 : ${timeFour - timeThree} : $num2") | |
val anotherFun: (Triple<Int, Int, Int>) -> Int = | |
{ triple -> myFun(triple.first) + myFun(triple.second) + myFun(triple.third) } | |
val addNums = Memoizer.memoize(anotherFun) | |
val startTime = System.currentTimeMillis() | |
addNums(Triple(1, 2, 3)) | |
val endTime = System.currentTimeMillis() | |
println("time taken : ${endTime - startTime}") | |
val startTime2 = System.currentTimeMillis() | |
addNums(Triple(1, 2, 3)) | |
val endTime2 = System.currentTimeMillis() | |
//outputs in approx zero time due to the key | |
println("time taken : ${endTime2 - startTime2}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment