View Source Xema.Utils (xema v0.17.4)

Some utilities for Xema.

Summary

Functions

Returns whether the given key exists in the given value.

Returns the size of a list or tuple.

Converts the given string to an existing atom. Returns nil if the atom does not exist.

Converts a map with integer keys or integer keys represented as strings to a sorted list.

Returns nil if uri_1 and uri_2 are nil. Parses a URI when the other URI is nil. Merges URIs if both are not nil.

Functions

@spec has_key?(map() | keyword() | [{String.t(), any()}], any()) :: boolean()

Returns whether the given key exists in the given value.

Returns true if

  • value is a map and contains key as a key.
  • value is a keyword and contains key as a key.
  • value is a list of tuples with keyas the first element.

Examples

  iex> alias Xema.Utils
  iex> Utils.has_key?(%{foo: 5}, :foo)
  true
  iex> Utils.has_key?([foo: 5], :foo)
  true
  iex> Utils.has_key?([{"foo", 5}], "foo")
  true
  iex> Utils.has_key?([{"foo", 5}], "bar")
  false
  iex> Utils.has_key?([], "bar")
  false
@spec size(list() | tuple()) :: integer()

Returns the size of a list or tuple.

@spec to_existing_atom(String.t() | atom()) :: atom() | nil

Converts the given string to an existing atom. Returns nil if the atom does not exist.

Examples

  iex> import Xema.Utils
  iex> to_existing_atom(:my_atom)
  :my_atom
  iex> to_existing_atom("my_atom")
  :my_atom
  iex> to_existing_atom("not_existing_atom")
  nil
Link to this function

to_sorted_list(map, opts \\ [keys: true])

View Source
@spec to_sorted_list(map(), [{:keys, boolean()}]) :: {:ok, list()} | :error

Converts a map with integer keys or integer keys represented as strings to a sorted list.

Returns an ok tuple with the list or an :error atom.

Options:

  • keys - if true the resulting list has {key, value} items, with false
         the list contains the values. Defaults to `[keys: true]`.

Examples

  iex> alias Xema.Utils
  iex> Utils.to_sorted_list(%{2 => "b", 3 => "c", 1 => "a"})
  {:ok, [{1, "a"}, {2, "b"}, {3, "c"}]}
  iex> Utils.to_sorted_list(%{"2" => "b", "3" => "c", "1" => "a"})
  {:ok, [{"1", "a"}, {"2", "b"}, {"3", "c"}]}
  iex> Utils.to_sorted_list(%{"2" => "b", "x" => "c", "1" => "a"})
  :error
  iex> Utils.to_sorted_list(%{"2" => "b", "3" => "c", "1" => "a"}, keys: true)
  {:ok, [{"1", "a"}, {"2", "b"}, {"3", "c"}]}
  iex> Utils.to_sorted_list(%{"2" => "b", "3" => "c", "1" => "a"}, keys: false)
  {:ok, ["a", "b", "c"]}
Link to this function

update_uri(uri_1, uri_2)

View Source
@spec update_uri(URI.t() | String.t() | nil, URI.t() | String.t() | nil) ::
  URI.t() | nil

Returns nil if uri_1 and uri_2 are nil. Parses a URI when the other URI is nil. Merges URIs if both are not nil.