Add Maybe.Extra.justIf
Maybe.Extra.justIf : Bool -> a -> Maybe a
justIf bool value =
if bool then
Just value
else
Nothing
Test.fuzz Fuzz.int "justIf False _ = Nothing" <|
\int ->
Maybe.Extra.justIf False int
|> Expect.equal Nothing
Test.fuzz Fuzz.int "justIf True a = Just a" <|
\int ->
Maybe.Extra.justIf True a
|> Expect.equal (Just a)
Motivating use case
I had a dropdown menu with a few actions for the user to choose. I needed to remove one of the actions from the list based on a boolean.
items =
[ { stuff = Stuff }
|> Maybe.Extra.justIf (not isArchived)
, Just { stuff = OtherStuff }
, Just { stuff = YouGetIt }
]
|> Maybe.Extra.values
Normally I'd do it with:
items =
[ if isArchived then
Nothing
else
Just { stuff = Stuff }
, Just { stuff = OtherStuff }
, Just { stuff = YouGetIt }
]
|> Maybe.Extra.values
Our code is full of this pattern.
Maybe there's also some Html.Attributes.classList-like way? I'm thinking List.Extra.filter : List (a, Bool) -> List a.
items =
[ ( { stuff = Stuff }, not isArchived )
, ( { stuff = OtherStuff }, True )
, ( { stuff = YouGetIt }, True )
]
|> List.Extra.filter
See also: https://github.com/elmcraft/core-extra/issues/55#issuecomment-2039509925
I think justIf is a way better name than toMaybe, fwiw
I think the classList style function for List.Extra would actually be a much more useful solution, that seems to come up a lot (especially in view code).