Packages
TMap is a library for manipulating map objects, useful for master data management systems it is possible to define rules for keys/values replace, adding new keys/values by regex matching on otehr keys/values,... See Plugins direcctory for details
Current section
Files
Jump to
Current section
Files
lib/map_utils.ex
defmodule MapUtils do
require Logger
@spec all_required_keys?(map, list) :: boolean
def all_required_keys?(map, list) when is_map(map) and is_list(list) do
keys = Map.keys(map)
ok = Enum.all?(list, fn k -> Enum.member?(keys, k) end)
if not ok do
Logger.error("Missing a required key among " <> inspect(list))
Logger.error(" in " <> inspect(map))
end
ok
end
@spec filter_keys_by_regex(map | nil, String.t() | nil) :: list
def filter_keys_by_regex(dict, regex) when is_nil(dict) or is_nil(regex) or map_size(dict) == 0,
do: []
def filter_keys_by_regex(dict, regex) when is_map(dict) and is_binary(regex) do
case RegexUtils.compile(regex) do
{:ok, regex} ->
filter_keys_by_regex(dict, regex)
{:error, error} ->
Logger.error("Wrong regex '" <> regex <> "': the error is: '" <> inspect(error))
[]
end
end
@spec filter_keys_by_regex(map, String.t()) :: list
def filter_keys_by_regex(dict, regex) when is_map(dict) do
ListUtils.filter_by_regex(Map.keys(dict), regex)
end
@spec match_keys_by_regex?(map, String.t()) :: boolean
def match_keys_by_regex?(dict, regex) when is_nil(dict) or is_nil(regex) or map_size(dict) == 0,
do: false
@spec match_keys_by_regex?(map, String.t()) :: boolean
def match_keys_by_regex?(dict, regex) when is_map(dict) do
Enum.count(filter_keys_by_regex(dict, regex)) > 0
end
@spec match_keys_values_by_regex?(map, String.t(), String.t()) :: boolean
def match_keys_values_by_regex?(dict, key_regex, value_regex)
when is_nil(dict) or is_nil(key_regex) or is_nil(value_regex) or map_size(dict) == 0,
do: false
@spec match_keys_values_by_regex?(map, String.t(), String.t()) :: boolean
def match_keys_values_by_regex?(dict, key_regex, value_regex) when is_map(dict) do
keys = filter_keys_by_regex(dict, key_regex)
values = Enum.map(keys, fn x -> dict[x] end)
values_without_nil = Enum.reject(values, &is_nil/1)
Enum.count(ListUtils.filter_by_regex(values_without_nil, value_regex)) > 0
end
@spec log(map, String.t()) :: map
def log(dict, text) when is_map(dict) do
key_log = "_log"
# key = :os.system_time(:seconds)
old_value = Map.get(dict, key_log, [])
new_value = [text | old_value]
Map.put(dict, key_log, new_value)
end
end