Last active
February 5, 2019 21:41
-
-
Save lucamug/5e234543a47df0754f1cf58ae8b5de67 to your computer and use it in GitHub Desktop.
Elm Example for https://medium.com/@l.mugnaini/things-that-can-go-wrong-without-a-strictly-typed-language-d91d418a53a1
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
<div id="app"></div> | |
<script src="js/elm.v.1.js"></script> | |
<script> | |
Elm.Main.init({ | |
node: document.getElementById("app"), | |
flags: { | |
url: "https://api.myjson.com/bins/74l63" | |
} | |
}); | |
</script> |
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
type alias Product = | |
{ id : Int | |
, quantity : Int | |
, name : String | |
} | |
type Msg | |
= GotProducts (Result Error (List Product)) | |
| ChangeQuantity Int String | |
update msg products = | |
case msg of | |
GotProducts (Ok newProducts) -> | |
( newProducts, Cmd.none ) | |
GotProducts (Err _) -> | |
( products, Cmd.none ) | |
ChangeQuantity productId newQuantity -> | |
let | |
newProducts = | |
List.map | |
(\product -> | |
if product.id == productId then | |
{ product | |
| quantity = | |
Maybe.withDefault product.quantity <| String.toInt newQuantity | |
} | |
else | |
product | |
) | |
products | |
in | |
( newProducts, Cmd.none ) | |
totalProducts products = | |
List.foldl (\product acc -> acc + product.quantity) 0 products | |
view products = | |
div [] <| | |
List.map | |
(\product -> | |
div [] | |
[ input | |
[ type_ "number" | |
, onInput <| ChangeQuantity product.id | |
, value <| String.fromInt product.quantity | |
] | |
[] | |
, button | |
[ onClick <| | |
ChangeQuantity product.id | |
(String.fromInt (product.quantity + 1)) | |
] | |
[ text "Add 1" ] | |
, text <| " " ++ product.name | |
] | |
) | |
products | |
++ [ p [] [ text <| "Total Inventory: " ++ (String.fromInt <| totalProducts products) ] | |
, p [] [ text <| "Quantities: " ++ encode 1 (Encode.list Encode.int (List.map .quantity products)) ] | |
] | |
productsDecoder = | |
field "products" <| | |
list <| | |
map3 Product | |
(field "id" int) | |
(field "quantity" int) | |
(field "name" string) | |
main : Program { url : String } (List Product) Msg | |
main = | |
element | |
{ init = | |
\flags -> | |
( [] | |
, get | |
{ url = flags.url | |
, expect = expectJson GotProducts productsDecoder | |
} | |
) | |
, view = view | |
, subscriptions = \_ -> Sub.none | |
, update = update | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment