forked from bryanjenningz/25-elm-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11-counters.elm
84 lines (69 loc) · 2.15 KB
/
11-counters.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
module Main exposing (..)
import Html exposing (Html, text, div, beginnerProgram, button)
import Html.Attributes exposing (class)
import Html.Events exposing (onClick)
-- We've added the (Decrement Int) value to the Msg union type.
-- (Decrement Int) will work in a similar way that (Increment Int) works
-- except it will decrement the counter at the specified index instead of
-- incrementing it.
type Msg
= Increment Int
| Decrement Int
| AddCount
type alias Model =
List Int
viewCount : Int -> Int -> Html Msg
viewCount index count =
div [ class "mb-2" ]
[ text (toString count)
, button
[ class "btn btn-primary ml-2", onClick (Increment index) ]
[ text "+" ]
-- We added a button that will trigger pass a (Decrement Int) message
-- to the update function when it's clicked.
, button
[ class "btn btn-primary ml-2", onClick (Decrement index) ]
[ text "-" ]
]
view : Model -> Html Msg
view model =
div [ class "text-center" ]
[ div [ class "mb-2" ]
[ button
[ class "btn btn-primary", onClick AddCount ]
[ text "Add Count" ]
]
, div [] (List.indexedMap viewCount model)
]
update : Msg -> Model -> Model
update msg model =
case msg of
Increment index ->
List.indexedMap
(\i count ->
if i == index then
count + 1
else
count
)
model
-- We added an expression that handles the (Decrement Int) message value,
-- which decrements the counter at the index that we care about.
Decrement index ->
List.indexedMap
(\i count ->
if i == index then
count - 1
else
count
)
model
AddCount ->
model ++ [ 0 ]
main : Program Never Model Msg
main =
beginnerProgram
{ model = [ 0, 0 ]
, view = view
, update = update
}