iT邦幫忙

2022 iThome 鐵人賽

DAY 20
0
Software Development

戀戀 Elixir系列 第 20

二十. Access Behaviour

  • 分享至 

  • xImage
  •  

You are working with a web development team to maintain a website for a local basketball team.

The web development team is less familiar with Elixir and is asking for a function to be able to extract data from a series of nested maps to facilitate rapid development.

1. Extract data from a nested map structure

Implement the extract_from_path/2 function to take two arguments:

data: a nested map structure with data about the basketball team.
path: a string consisting of period-delimited keys to obtain the value associated with the last key.

If the value or the key does not exist at any point in the path, nil should be returned.
Use the Access Behaviour when implementing this function.

Do not use any Map or Kernel module functions for working with the nested map data structure.

2. Refactor using included functions

Your coworker reviewing your code tells you about a Kernel module function which does something very similar to your implementation.

Implement get_in_path/2 to use this Kernel module function.

The arguments expected are the same as part 1.


https://exercism.org/tracks/elixir/exercises/basketball-website

defmodule BasketballWebsite do
  @moduledoc """
  practice Access Behaviour
  """

  @doc """
  get value depends on the given path
  """
  def extract_from_path(data, path), do: get_value_by_path(data, path_list(path))

  def get_in_path(data, path), do: get_in(data, path_list(path))

  defp get_value_by_path(value, []), do: value
  defp get_value_by_path(data, [head | tail]), do: get_value_by_path(data[head], tail)

  defp path_list(path), do: String.split(path, ".", trim: true)
end


上一篇
十九. Dates and Time
下一篇
二十ㄧ. Enum
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言