Last active
November 7, 2015 19:14
-
-
Save azazdeaz/f8047669e8e7719fab2b to your computer and use it in GitHub Desktop.
Elm - select a random item from a list on every button click
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
import Html exposing (..) | |
import Html.Events exposing (..) | |
import Signal | |
import Time | |
import Random | |
import Array | |
buttonMailbox = | |
Signal.mailbox () | |
buttonClicks : Signal Int | |
buttonClicks = | |
Time.timestamp buttonMailbox.signal | |
|> Signal.map fst | |
|> Signal.map round | |
values : List String | |
values = ["foo","bar","qux","fux","tux"] | |
view time = | |
let | |
seed = Random.initialSeed time | |
lastItem = List.length values - 1 | |
generator = Random.int 0 lastItem | |
randomIndex = fst (Random.generate generator seed) | |
getValue item = | |
case item of | |
Just i | |
-> i | |
Nothing | |
-> "error" | |
value = values | |
|> Array.fromList | |
|> Array.get randomIndex | |
|> getValue | |
in | |
div [] [ | |
text (toString values), | |
div [] [text (toString randomIndex ++ " / " ++ toString lastItem)], | |
div [] [text value], | |
button [on "click" targetValue (\_ -> Signal.message buttonMailbox.address ()) ] [text "Surprise!"] | |
] | |
main = | |
Signal.map view buttonClicks |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment