Skip to content

Commit

Permalink
add an ID field to Player
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianHicks committed Apr 5, 2021
1 parent 054ad83 commit c37c473
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
1 change: 1 addition & 0 deletions elm.json
Expand Up @@ -14,6 +14,7 @@
"elm/json": "1.1.3",
"elm/random": "1.0.0",
"ohanhi/keyboard": "2.0.1",
"robinheghan/murmur3": "1.0.0",
"rtfeldman/elm-css": "16.1.0",
"tesk9/accessible-html-with-css": "2.1.1"
},
Expand Down
20 changes: 15 additions & 5 deletions src/Player.elm
Expand Up @@ -3,18 +3,21 @@ module Player exposing (Player, decoder, encode, incrementMatchesPlayed, init, s
import Elo
import Json.Decode as Decode exposing (Decoder)
import Json.Encode as Encode exposing (Value)
import Murmur3


type alias Player =
{ name : String
{ id : Int
, name : String
, rating : Int
, matches : Int
}


init : String -> Player
init name =
{ name = name
{ id = Murmur3.hashString 0 name
, name = name
, rating = Elo.initialRating
, matches = 0
}
Expand All @@ -32,16 +35,23 @@ incrementMatchesPlayed player =

decoder : Decoder Player
decoder =
Decode.map3 Player
Decode.map4 Player
(Decode.oneOf
[ Decode.field "id" Decode.int
, Decode.field "name" Decode.string
|> Decode.map (Murmur3.hashString 0)
]
)
(Decode.field "name" Decode.string)
(Decode.field "rating" Decode.int)
(Decode.field "matches" Decode.int)


encode : Player -> Value
encode { name, rating, matches } =
encode { id, name, rating, matches } =
Encode.object
[ ( "name", Encode.string name )
[ ( "id", Encode.int id )
, ( "name", Encode.string name )
, ( "rating", Encode.int rating )
, ( "matches", Encode.int matches )
]
23 changes: 22 additions & 1 deletion tests/PlayerTest.elm
Expand Up @@ -3,6 +3,8 @@ module PlayerTest exposing (..)
import Expect
import Fuzz exposing (Fuzzer)
import Json.Decode as Decode
import Json.Encode as Encode
import Murmur3
import Player exposing (Player)
import Test exposing (..)

Expand All @@ -18,7 +20,8 @@ roundTripDecoderTest =

playerFuzzer : Fuzzer Player
playerFuzzer =
Fuzz.map3 Player
Fuzz.map4 Player
(Fuzz.map (Murmur3.hashString 0) nameFuzzer)
nameFuzzer
(Fuzz.intRange 1000 3000)
(Fuzz.intRange 0 50)
Expand All @@ -33,3 +36,21 @@ nameFuzzer =
in
Fuzz.map2 (::) chars (Fuzz.list chars)
|> Fuzz.map String.fromList


decoderTest : Test
decoderTest =
describe "decoder"
[ describe "id"
[ test "fills in the ID if it's missing" <|
\_ ->
Encode.object
[ ( "name", Encode.string "Test" )
, ( "rating", Encode.int 1200 )
, ( "matches", Encode.int 0 )
]
|> Decode.decodeValue Player.decoder
|> Result.map .id
|> Expect.equal (Ok 123038886)
]
]

0 comments on commit c37c473

Please sign in to comment.