LRUCache

This module provides a cache for key/value pairs. When the maximum size is reached, the least-recently-used key/value pair is evicted from the cache.

Example:

myCache =
    LRUCache.newLRUCache 3
        |> LRUCache.put "a" 1
        |> LRUCache.put "b" 2
        |> LRUCache.put "c" 3
        |> LRUCache.put "d" 4

-- "a" was evicted
LRUCache.get "a" => {cache: newCacheState, value: Nothing}
LRUCache.get "b" => {cache: newCacheState, value: Just 2}
LRUCache.get "c" => {cache: newCacheState, value: Just 3}
LRUCache.get "d" => {cache: newCacheState, value: Just 4}
type LRUCache comparable v

LRUCache is the type which is the actual cache. Create one with newLRUCache

newLRUCache : Int -> LRUCache comparable v

Create the LRUCache, setting the maximum size.

newLRUCache 100 ->  LRUCache

Example:

import LRUCache exposing (LRUCache)

type alias Model =
    { cache : LRUCache
    }

initialModel =
    { cache = LRUCache.newCache 100
    }
toDict : LRUCache comparable v -> Dict comparable v

Get a Dict that represents this cache, without any history of which keys were most recently used. This is useful for unit tests. As a user of the package, you're unlikely to use toDict.

toDict lruCache -> Dict
put :
comparable
-> v
-> LRUCache comparable v
-> LRUCache comparable v

Insert, or update, a key/value pair. This marks the key as most recently used.

put "new-entry" 10 lruCache -> LRUCache

Example:

    let
        newCache = LRUCache.put "new-entry" 10 model.cache
    in
        { model
            | cache = newCache
        }
get :
comparable
-> LRUCache comparable v
-> { cache : LRUCache comparable v, value : Maybe v
}

Maybe get a value for the given key. If the key exists, it is makred as most recently used.

get key lruCache -> { cache: LRUCache, value: Maybe value }

Example:

    let
        {cache: newCache, value: maybeValue } = LRUCache.get "new-entry" model.cache
    in
        when maybeValue is
            Nothing ->
                { model
                    | cache = newCache
                }, Cmd.none

            Just value ->
                { model
                    | cache = newCache
                    , results = value
                }, Cmd.none
remove :
comparable
-> LRUCache comparable v
-> LRUCache comparable v

Remove a key from the cache. If the key doesn't exist, no harm is done.

remove key lruCache -> LRUCache

Example:

    let
        newCache = LRUCache.remove "new-entry" model.cache
    in
        { model
            | cache = newCache
        }