iT邦幫忙

2022 iThome 鐵人賽

DAY 15
0
Software Development

戀戀 Elixir系列 第 15

十五. If Statement

  • 分享至 

  • xImage
  •  

In this exercise you'll be writing code to print name badges for factory employees. Employees have an ID, name, and department name.

Employee badge labels are formatted as follows: "[id] - name - DEPARTMENT".

1. Print a badge for an employee

Implement the NameBadge.print/3 function. It should take an id, name, and a department. It should return the badge label, with the department name in uppercase.

2. Print a badge for a new employee

Due to a quirk in the computer system, new employees occasionally don't yet have an ID when they start working at the factory. As badges are required, they will receive a temporary badge without the ID prefix.

Extend the NameBadge.print/3 function. When the id is missing, it should print a badge without it.

3. Print a badge for the owner

Even the factory's owner has to wear a badge at all times. However, an owner does not have a department. In this case, the label should print "OWNER" instead of the department name.

Extend the NameBadge.print/3 function. When the department is missing, assume the badge belongs to the company owner.

Note that it is possible for the owner to also be a new employee.


https://exercism.org/tracks/elixir/exercises/name-badge

defmodule NameBadge do
  @moduledoc """
  if else condition and nil
  """
  @owner "OWNER"
  @middle_separator " - "

  def print(id, name,department) do
    id = if id, do: "[#{id}]"
    department = if department, do: "#{String.upcase(department)}", else: @owner

    [id, name, department]
      |> Enum.reject(fn value -> value === nil end)
      |> Enum.map_join(@middle_separator, &(&1))
  end

  # @doc """
  # practice with if else condition
  # """
  # @spec print(integer() | nil, String.t(), String.t() | nil) :: String.t()
  # def print(id, name, department) do
  #   id = if id, do: "[#{id}] - "
  #   department = if department, do: "#{String.upcase(department)}", else: "OWNER"

  #   "#{id}#{name} - #{department}"
  # end
end

上一篇
十四. IO
下一篇
十六. Processes
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言