Julia LRU cache with a bounded size
Julia
mutable struct LRUCache{K,V}
limit::Int
data::Dict{K,V}
order::Vector{K}
end
LRUCache{K,V}(limit::Int) where {K,V} = LRUCache{K,V}(limit, Dict{K,V}(), K[])
function cached!(c::LRUCache{K,V}, key::K, compute) where {K,V}
if haskey(c.data, key)
filter!(k -> k != key, c.order)
push!(c.order, key)
return c.data[key]
end
length(c.order) >= c.limit && delete!(c.data, popfirst!(c.order))
c.data[key] = compute()
push!(c.order, key)
return c.data[key]
end
cache = LRUCache{String,Int}(2)
println(cached!(cache, "a", () -> 1), cached!(cache, "b", () -> 2))