Skip to content

Instantly share code, notes, and snippets.

@damonvjanis
Created October 17, 2018 19:08
Show Gist options
  • Save damonvjanis/17d9380eaae28e76cb515e8714f48525 to your computer and use it in GitHub Desktop.
Save damonvjanis/17d9380eaae28e76cb515e8714f48525 to your computer and use it in GitHub Desktop.
An Elixir util module to translate US two letter state codes to state names, and state names to two letter codes.
defmodule States do
@moduledoc """
A util that allows you to search for the uppercase abbreviation
of a state by name (case insensitive) or the capitalized name
of a state by abbreviation (case insensitive).
"""
@states_to_abbr %{
"Alabama" => "AL",
"Alaska" => "AK",
"Arizona" => "AZ",
"Arkansas" => "AR",
"California" => "CA",
"Colorado" => "CO",
"Connecticut" => "CT",
"Delaware" => "DE",
"District of Columbia" => "DC",
"Florida" => "FL",
"Georgia" => "GA",
"Hawaii" => "HI",
"Idaho" => "ID",
"Illinois" => "IL",
"Indiana" => "IN",
"Iowa" => "IA",
"Kansas" => "KS",
"Kentucky" => "KY",
"Louisiana" => "LA",
"Maine" => "ME",
"Maryland" => "MD",
"Massachusetts" => "MA",
"Michigan" => "MI",
"Minnesota" => "MN",
"Mississippi" => "MS",
"Missouri" => "MO",
"Montana" => "MT",
"Nebraska" => "NE",
"Nevada" => "NV",
"New Hampshire" => "NH",
"New Jersey" => "NJ",
"New Mexico" => "NM",
"New York" => "NY",
"North Carolina" => "NC",
"North Dakota" => "ND",
"Northern Mariana Islands" => "MP",
"Ohio" => "OH",
"Oklahoma" => "OK",
"Oregon" => "OR",
"Palau" => "PW",
"Pennsylvania" => "PA",
"Puerto Rico" => "PR",
"Rhode Island" => "RI",
"South Carolina" => "SC",
"South Dakota" => "SD",
"Tennessee" => "TN",
"Texas" => "TX",
"Utah" => "UT",
"Vermont" => "VT",
"Virgin Islands" => "VI",
"Virginia" => "VA",
"Washington" => "WA",
"West Virginia" => "WV",
"Wisconsin" => "WI",
"Wyoming" => "WY"
}
# Swaps the keys and values of @states_to_abbr
@abbr_to_states Enum.into(@states_to_abbr, %{}, fn {k, v} -> {v, k} end)
@doc """
Takes a state name (case insensitve) and returns a two letter
abbreviation (uppercase) if a match is found, or nil otherwise.
"""
def state_to_abbr(state) do
state = String.downcase(state)
Enum.find_value(@states_to_abbr, &if(String.downcase(elem(&1, 0)) == state, do: elem(&1, 1)))
end
@doc """
Takes a two letter abbreviation (case insensitve) and returns
a capitalized state name if found, or nil otherwise.
"""
def abbr_to_state(abbr) do
abbr = String.upcase(abbr)
Enum.find_value(@abbr_to_states, &if(elem(&1, 0) == abbr, do: elem(&1, 1)))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment