String concat pattern matching

I have an application that wants to print out a specific format for location data. The data will sometimes be available.

I have an application that wants to print out a specific format for location data. The location data, has minimum requirements. You don’t have to provide all the fields, but the ones you provide we want to format the string in a specific way.

The <> operator concats Strings together. If you combine this with pattern matching, you can print out specific formats based on the key/value pairs of a Map.

In the example below we are going to format a location


defmodule Formatter do

  def formatted_location(%{city: "", region: "", country: country}) do
    country
  end

  def formatted_location(%{city: "", region: region, country: country}) do
    region <> ", " <> country
  end

  def formatted_location(%{city: city, region: region, country: country}) do
    city <> ", " <> region <> ", " <> country
  end

end

Create some dummy data

a = %{city: "", region: "", country: "United States of America"}
b = %{city: "", region: "West US", country: "United States of America"}
c = %{city: "Los Angeles", region: "West US", country: "United States of America"}

iex> Formatter.formatted_location(a)
# "United States of America"

iex> Formatter.formatted_location(b)
# "West US, United States of America"

iex> Formatter.formatted_location(c)
# "Los Angeles, West US, United States of America"

What I like about pattern matching is the ability to add variations to formatted_location/1 all within one file location.

Pattern matching can be a helpful approach for front end development problems such as this example shown.