Last active
November 19, 2019 04:15
-
-
Save Warry/b4382a5b4373de57f5ba to your computer and use it in GitHub Desktop.
Convert a List of objects into a Dict (≈ Map) using an object's property as key, in a type safe way with ELM
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 Dict | |
-- The transformation function | |
listToDict : (a -> comparable) -> [a] -> Dict.Dict comparable a | |
listToDict getKey values = Dict.fromList (map (\v -> (getKey v, v)) values) | |
-- Demo type | |
type FooBar = | |
{ foo : String | |
, bar : Int | |
} | |
-- Demo data | |
fooBars : [FooBar] | |
fooBars = | |
[ { foo = "tata", bar = 1 } | |
, { foo = "tete", bar = 2 } | |
, FooBar "titi" 3 | |
, FooBar "toto" 4 | |
] | |
-- Transform demo List to a Dict, using the `foo` property (String) | |
dict : Dict.Dict String FooBar | |
dict = listToDict .foo fooBars -- .foo is safe here | |
-- Transform demo List to a Dict, using the `bar` property (Int) | |
dict2 : Dict.Dict Int FooBar -- So is Int here ! | |
dict2 = listToDict .bar fooBars | |
-- Won't compile: | |
-- err : Dict.Dict Boolean FooBar | |
-- err = listToDict .bar fooBars | |
-- err : Dict.Dict String FooBar | |
-- err = listToDict .bazzzzzzz fooBars | |
-- Render result | |
main = flow down [ (asText dict), (asText dict2) ] |
Hey Warry, we're looking to use this snippet for something at work, and while it's a boring question, I have to ask—what code is this snippet license under?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An answer to : https://gist.github.com/srenault/3a8b08b73abb5bc520d3