-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemperatureConverter.gren
136 lines (111 loc) · 2.96 KB
/
TemperatureConverter.gren
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
module TemperatureConverter exposing ( main )
import Browser
import Html exposing ( Html )
import Html.Attributes as Attribute
import Html.Events as Event
import Layout exposing ( box, cluster )
main =
Browser.sandbox
{ init = init
, update = update
, view = view
}
type alias Model =
{ celsius : String
, fahrenheit : String
}
init : Model
init =
{ celsius = "1.0"
, fahrenheit = "1.0"
}
type Msg
= OnInputCelsius String
| OnInputFahrenheit String
update : Msg -> Model -> Model
update msg model =
case msg of
OnInputCelsius celsius ->
{ celsius = celsius
, fahrenheit =
celsius
|> String.toFloat
|> Maybe.map celsiusToFahrenheit
|> Maybe.map String.fromFloat
|> Maybe.withDefault model.fahrenheit
}
OnInputFahrenheit fahrenheit ->
{ celsius =
fahrenheit
|> String.toFloat
|> Maybe.map fahrenheitToCelsius
|> Maybe.map String.fromFloat
|> Maybe.withDefault model.celsius
, fahrenheit = fahrenheit
}
celsiusToFahrenheit : Float -> Float
celsiusToFahrenheit celsius =
celsius * (9.0 / 5.0) + 32.0
fahrenheitToCelsius : Float -> Float
fahrenheitToCelsius fahrenheit =
(fahrenheit - 32) * (5.0 / 9.0)
view : Model -> Html Msg
view model =
let
celsius =
inputProperties "celsius" "Celsius" model.celsius OnInputCelsius
fahrenheit =
inputProperties "fahrenheit" "Fahrenheit" model.fahrenheit OnInputFahrenheit
in
Html.div
[]
[ box
[ cluster
[ formControl celsius
, Html.p
[]
[ Html.text "="
]
, formControl fahrenheit
]
]
]
type alias InputProperties =
{ id : String
, label : String
, value : String
, onInput : String -> Msg
}
inputProperties : String -> String -> String -> (String -> Msg) -> InputProperties
inputProperties id label value onInput =
{ id = id
, label = label
, value = value
, onInput = onInput
}
formControl : InputProperties -> Html Msg
formControl control =
let
{ id, label, value, onInput } =
control
in
Html.div
[ Attribute.class "display:contents"
]
[ Html.input
[ Attribute.style "text-align" "end"
, Attribute.id id
, Attribute.type_ "number"
, Attribute.step "0.1"
, Attribute.placeholder "0.0"
, Attribute.value value
, Event.onInput onInput
]
[ Html.text value
]
, Html.label
[ Attribute.for id
]
[ Html.text label
]
]