Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refactoring a pipeline of Maybe.map functions in Elm

Refactoring maybe code in Elm

Given this ugly series of cases:

optionalFormattedFriendAddress : Maybe Friend -> Maybe String
optionalFormattedFriendAddress maybeFriend =
  let
    maybeAddress = case maybeFriend of
      Just friend -> Just friend.address
      Nothing -> Nothing

    maybeLine1 = case maybeAddress of
      Just address -> Just address.line1
      Nothing -> Nothing

  in
    case maybeLine1 of
      Just line1 -> Just (String.toUpper line1)
      Nothing -> Nothing

I can refactor to a pipeline of maps:

maybeFriend
  |> Maybe.map .address
  |> Maybe.map .line1
  |> Maybe.map String.toUpper

Map functions compose so it can be flattened to:

maybeFriend
  |> Maybe.map (String.toUpper << .line1 << .adddress)

This can finally be extracted to a function:

formattedAddress : Friend -> String
formattedAddress friend =
  String.toUpper friend.address.line1
  
optionalFormattedFriendAddress : Maybe Friend -> Maybe String
optionalFormattedFriendAddress maybeFriend =
  Maybe.map formattedAddress maybeFriend
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment