DEV Community

Discussion on: Daily Challenge #296 - Years to Centuries

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited
defmodule Year do
  @doc """
  Returns the stringified, suffixed form of a numeric year.

  Use `to_century/1` if you need to do further numeric work on the
  century number before (or in lieu of) using it as a string.

  ## Examples

      iex> Year.centurify(8120)
      "82nd"
      iex> Year.centurify(30200)
      "303rd"
      iex> Year.centurify(1601)
      "17th"
      iex> Year.centurify(2020)
      "21st"
      iex> Year.centurify(3030)
      "31st"
      iex> Year.centurify(1900)
      "20th"
      iex> Year.centurify(1776)
      "18th"
  """
  def centurify(year) do 
    century = to_century(year)
    "#{century}#{suffix(century)}"
  end

  def to_century(year), do: div(year, 100) + 1

  defp suffix(number) when number >= 100, 
    do: number |> rem(100) |> suffix
  defp suffix(number) when number in 11..13, do: "th"
  defp suffix(number) do
    case rem(number, 10) do
      1 -> "st"
      2 -> "nd"
      3 -> "rd"
      _ -> "th"
    end
  end
end

defmodule YearTest do
  import ExUnit.Case
  doctest Year
end
Enter fullscreen mode Exit fullscreen mode