Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created November 26, 2023 17:21
Show Gist options
  • Save PeterWaIIace/534351cad9a6560b814c9b04f476fcd3 to your computer and use it in GitHub Desktop.
Save PeterWaIIace/534351cad9a6560b814c9b04f476fcd3 to your computer and use it in GitHub Desktop.
Elm multi-form for units conversions
module Main exposing (main)
import Browser
import Html exposing (Html, Attribute, p, span, input, text)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ input_c : String,
input_f : String,
input_m : String
}
init : Model
init =
{ input_c = "",
input_f = "",
input_m = ""
}
-- UPDATE
type Msg
= ChangeCelsius String
| ChangeFarenheit String
| ChangeMeter String
update : Msg -> Model -> Model
update msg model =
case msg of
ChangeCelsius newInput ->
{ model | input_c = newInput }
ChangeFarenheit newInput ->
{ model | input_f = newInput }
ChangeMeter newInput ->
{ model | input_m = newInput }
-- Formulas
c2f : Float -> Float
c2f input =
input * 1.8 + 32
f2c : Float -> Float
f2c input =
(input - 32) / 1.8
m2inch : Float -> Float
m2inch input =
input * 39.3701
-- VIEW
convert : Float -> (Float -> Float) -> String
convert input formula =
String.fromFloat (formula input)
viewConverter : String -> (Float -> Float) -> (String -> Msg) -> String -> String -> Html Msg
viewConverter input formula onInputChange firstVal convVal =
case String.toFloat input of
Just value ->
viewHelper input "blue" onInputChange (convert value formula) firstVal convVal
Nothing ->
viewHelper input "red" onInputChange "???" firstVal convVal
viewHelper : String -> String -> (String -> Msg) -> String -> String -> String -> Html Msg
viewHelper userInput color onInputChange convertedValue firstVal convVal =
span []
[ input [ value userInput, onInput onInputChange, style "width" "40px", style "border-color" color ] []
, text firstVal
, span [ style "color" color ] [ text convertedValue ]
, text convVal
]
view : Model -> Html Msg
view model =
p []
[
viewConverter model.input_c c2f ChangeCelsius "°C = " "°F"
,viewConverter model.input_f f2c ChangeFarenheit "°F = " "°C"
,viewConverter model.input_m m2inch ChangeMeter "m = " "inch"
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment