elmcraft / core-extra

Utility functions for an improved experience with elm/core
https://package.elm-lang.org/packages/elmcraft/core-extra/latest/
Other
23 stars 11 forks source link

Add Maybe.Extra.justIf #56

Closed Janiczek closed 2 months ago

Janiczek commented 5 months ago

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
lydell commented 5 months ago

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

miniBill commented 5 months ago

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

gampleman commented 5 months ago

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