Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Maybe.Extra.justIf #56

Closed
Janiczek opened this issue Apr 18, 2024 · 3 comments · Fixed by #63
Closed

Add Maybe.Extra.justIf #56

Janiczek opened this issue Apr 18, 2024 · 3 comments · Fixed by #63
Labels
new function Request to add a new function to the library

Comments

@Janiczek
Copy link
Contributor

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 Janiczek added the new function Request to add a new function to the library label Apr 18, 2024
@lydell
Copy link
Contributor

lydell commented Apr 18, 2024

See also: #55 (comment)

@miniBill
Copy link
Collaborator

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

@gampleman
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new function Request to add a new function to the library
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants