2023-02-08 15:52:54 +00:00
|
|
|
module Internal.Tools.Hashdict exposing (..)
|
|
|
|
|
|
|
|
{-| This module abstracts the `Dict` type with one function that chooses the unique identifier for each type.
|
|
|
|
|
|
|
|
For example, this is used to store events by their event id, or store rooms by their room id.
|
|
|
|
|
|
|
|
-}
|
|
|
|
|
2023-11-03 21:44:29 +00:00
|
|
|
import FastDict as Dict exposing (Dict)
|
|
|
|
import Json.Decode as D
|
|
|
|
import Json.Encode as E
|
|
|
|
import Hash exposing (Hash)
|
2023-02-08 15:52:54 +00:00
|
|
|
|
|
|
|
type Hashdict a
|
|
|
|
= Hashdict
|
|
|
|
{ hash : a -> String
|
|
|
|
, values : Dict String a
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
empty : (a -> String) -> Hashdict a
|
|
|
|
empty hash =
|
|
|
|
Hashdict { hash = hash, values = Dict.empty }
|
|
|
|
|
2023-11-03 21:44:29 +00:00
|
|
|
encode : Hashdict E.Value -> E.Value
|
|
|
|
encode (Hashdict h) =
|
|
|
|
h.values
|
|
|
|
|> Dict.toList
|
|
|
|
|> E.object
|
|
|
|
|
2023-02-08 15:52:54 +00:00
|
|
|
|
2023-03-01 14:58:40 +00:00
|
|
|
fromList : (a -> String) -> List a -> Hashdict a
|
|
|
|
fromList hash xs =
|
|
|
|
Hashdict
|
|
|
|
{ hash = hash
|
|
|
|
, values =
|
|
|
|
xs
|
|
|
|
|> List.map (\x -> ( hash x, x ))
|
|
|
|
|> Dict.fromList
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-02-08 15:52:54 +00:00
|
|
|
get : String -> Hashdict a -> Maybe a
|
|
|
|
get k (Hashdict h) =
|
|
|
|
Dict.get k h.values
|
|
|
|
|
|
|
|
|
|
|
|
insert : a -> Hashdict a -> Hashdict a
|
|
|
|
insert v (Hashdict h) =
|
|
|
|
Hashdict { h | values = Dict.insert (h.hash v) v h.values }
|
|
|
|
|
|
|
|
|
|
|
|
keys : Hashdict a -> List String
|
|
|
|
keys (Hashdict h) =
|
|
|
|
Dict.keys h.values
|
|
|
|
|
2023-11-03 21:44:29 +00:00
|
|
|
toList : Hashdict a -> List (String, a)
|
|
|
|
toList (Hashdict h) =
|
|
|
|
Dict.toList h.values
|
2023-02-08 15:52:54 +00:00
|
|
|
|
2023-03-01 14:58:40 +00:00
|
|
|
union : Hashdict a -> Hashdict a -> Hashdict a
|
|
|
|
union (Hashdict h1) (Hashdict h2) =
|
|
|
|
Hashdict
|
|
|
|
{ hash = h1.hash
|
|
|
|
, values = Dict.union h1.values h2.values
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-02-08 15:52:54 +00:00
|
|
|
values : Hashdict a -> List a
|
|
|
|
values (Hashdict h) =
|
|
|
|
Dict.values h.values
|