org.jetbrains.kotlinx.jupyter.util.Memoization.kt Maven / Gradle / Ivy
package org.jetbrains.kotlinx.jupyter.util
import java.util.Optional
import java.util.concurrent.ConcurrentHashMap
fun createCachedFun(calculate: (A) -> V): (A) -> V {
return createCachedFun({ it }, calculate)
}
fun createCachedFun(
calculateKey: (A) -> K,
calculate: (A) -> V,
): (A) -> V {
val cache = ConcurrentHashMap, Optional>()
@Suppress("UNCHECKED_CAST")
return { argument ->
val key = Optional.ofNullable(calculateKey(argument)) as Optional
cache.getOrPut(key) {
Optional.ofNullable(calculate(argument)) as Optional
}.orElse(null)
}
}