mirror of
https://github.com/dillonkearns/elm-pages-v3-beta.git
synced 2024-12-26 13:21:42 +03:00
Add oneOf.
This commit is contained in:
parent
ad3af69dbd
commit
54bb39f182
@ -1,4 +1,4 @@
|
||||
module QueryParams exposing (Parser, QueryParams, fromString, optionalString, parse, string, strings, toDict)
|
||||
module QueryParams exposing (Parser, QueryParams, fail, fromString, map2, oneOf, optionalString, parse, string, strings, succeed, toDict)
|
||||
|
||||
import Dict exposing (Dict)
|
||||
import Url
|
||||
@ -12,6 +12,44 @@ type Parser a
|
||||
= Parser (Dict String (List String) -> Result String a)
|
||||
|
||||
|
||||
succeed : a -> Parser a
|
||||
succeed value =
|
||||
Parser (\_ -> Ok value)
|
||||
|
||||
|
||||
fail : String -> Parser a
|
||||
fail errorMessage =
|
||||
Parser (\_ -> Err errorMessage)
|
||||
|
||||
|
||||
oneOf : List (Parser a) -> Parser a
|
||||
oneOf parsers =
|
||||
Parser
|
||||
(tryParser parsers)
|
||||
|
||||
|
||||
tryParser : List (Parser a) -> Dict String (List String) -> Result String a
|
||||
tryParser parsers dict =
|
||||
case parsers of
|
||||
[] ->
|
||||
Err ""
|
||||
|
||||
(Parser nextParser) :: otherParsers ->
|
||||
case nextParser dict of
|
||||
Ok okValue ->
|
||||
Ok okValue
|
||||
|
||||
Err _ ->
|
||||
tryParser otherParsers dict
|
||||
|
||||
|
||||
map2 : (a -> b -> combined) -> Parser a -> Parser b -> Parser combined
|
||||
map2 func (Parser a) (Parser b) =
|
||||
Parser <|
|
||||
\dict ->
|
||||
Result.map2 func (a dict) (b dict)
|
||||
|
||||
|
||||
optionalString : String -> Parser (Maybe String)
|
||||
optionalString key =
|
||||
custom key
|
||||
|
@ -42,4 +42,24 @@ all =
|
||||
[ ( "q", [ "mySearch1", "mySearch2" ] )
|
||||
]
|
||||
)
|
||||
, test "oneOf with no parsers" <|
|
||||
\() ->
|
||||
"q=mySearch1&q=mySearch2"
|
||||
|> QueryParams.fromString
|
||||
|> QueryParams.parse (QueryParams.oneOf [])
|
||||
|> Expect.equal (Err "")
|
||||
, test "oneOf with two parsers" <|
|
||||
\() ->
|
||||
"first=Jane&last=Doe"
|
||||
|> QueryParams.fromString
|
||||
|> QueryParams.parse
|
||||
(QueryParams.oneOf
|
||||
[ QueryParams.string "fullName"
|
||||
, QueryParams.map2
|
||||
(\first last -> first ++ " " ++ last)
|
||||
(QueryParams.string "first")
|
||||
(QueryParams.string "last")
|
||||
]
|
||||
)
|
||||
|> Expect.equal (Ok "Jane Doe")
|
||||
]
|
||||
|
Loading…
Reference in New Issue
Block a user