Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Forked from pfitz/ChildAges.elm
Last active July 26, 2016 07:46
Show Gist options
  • Save cobalamin/5643c3aadf02743b77e6b63b5bbba9d7 to your computer and use it in GitHub Desktop.
Save cobalamin/5643c3aadf02743b77e6b63b5bbba9d7 to your computer and use it in GitHub Desktop.
Add more beutifil
module ChildAges exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
import Html.App
import String
import Array
-- view
printOptionSelected : Int -> Int -> Html Msg
printOptionSelected sel n =
option [ selected (n == sel) ] [ text (toString n) ]
numberOfChildrenSelect : Model -> List (Html Msg)
numberOfChildrenSelect model =
[ label [] [ text "Anzahl der Kinder" ]
, select [ onInput numberChangedHandler ]
(List.map (printOptionSelected <| List.length model.alterDerKinder) [0..6])
]
ageSelect : Int -> Int -> Html Msg
ageSelect i age =
div []
[ label [] [ text "Alter der Kinder" ]
, select [ onInput (childAgeDidChangeHandler i) ]
(List.map (printOptionSelected age) [1..18])
]
ageSelects : Model -> List (Html Msg)
ageSelects model =
List.indexedMap ageSelect model.alterDerKinder
view : Model -> Html Msg
view model =
div []
(ageSelects model
++ numberOfChildrenSelect model
)
-- model
type alias Model =
{ alterDerKinder : List Int }
model : Model
model =
{ alterDerKinder = [ 3, 4 ] }
-- update
type Msg
= NumberOfKidsDidChanged Int
| AgeOfKidChanged Int Int
update : Msg -> Model -> Model
update msg model =
case msg of
NumberOfKidsDidChanged newListLength ->
case newListLength of
0 ->
{ model | alterDerKinder = [] }
_ ->
let
difference =
(List.length model.alterDerKinder) - newListLength
newAgeList =
-- fewer kids
if difference > 0 then
List.take newListLength model.alterDerKinder
-- more kids
else if difference < 0 then
addNEntriesToList model.alterDerKinder (abs difference)
else
model.alterDerKinder
in
{ model | alterDerKinder = newAgeList }
AgeOfKidChanged value nth ->
{ model | alterDerKinder = insertAt nth value model.alterDerKinder }
addNEntriesToList : List Int -> Int -> List Int
addNEntriesToList list entriesToAdd =
list ++ (List.repeat entriesToAdd 1)
numberChangedHandler : String -> Msg
numberChangedHandler numStrg =
case String.toInt numStrg of
Ok num ->
NumberOfKidsDidChanged num
Err err ->
NumberOfKidsDidChanged 0
childAgeDidChangeHandler : Int -> String -> Msg
childAgeDidChangeHandler nth valueString =
case String.toInt valueString of
Ok num ->
AgeOfKidChanged num nth
Err err ->
AgeOfKidChanged 0 0
insertAt : Int -> Int -> List Int -> List Int
insertAt nth value list =
list
|> Array.fromList
|> Array.set nth value
|> Array.toList
-- main
main : Program Never
main =
Html.App.beginnerProgram
{ model = model
, view = view
, update = update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment