core-extra icon indicating copy to clipboard operation
core-extra copied to clipboard

Add Maybe.Extra.justIf

Open Janiczek opened this issue 1 year ago • 3 comments

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

Janiczek avatar Apr 18 '24 12:04 Janiczek

See also: https://github.com/elmcraft/core-extra/issues/55#issuecomment-2039509925

lydell avatar Apr 18 '24 13:04 lydell

I think justIf is a way better name than toMaybe, fwiw

miniBill avatar Apr 18 '24 21:04 miniBill

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).

gampleman avatar Apr 19 '24 15:04 gampleman