Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created February 9, 2018 15:52
Show Gist options
  • Save JoelQ/df3b6ac80b9623d797217a4e58cc3ad0 to your computer and use it in GitHub Desktop.
Save JoelQ/df3b6ac80b9623d797217a4e58cc3ad0 to your computer and use it in GitHub Desktop.
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