Current section
Files
Jump to
Current section
Files
lib/structs/entity_references_collection.ex
defmodule Manganese.EntityKit.Structs.EntityReferencesCollection do
alias Manganese.EntityKit.Structs
@type t :: %Structs.EntityReferencesCollection{
entity_ids: %{ optional(atom) => term }
}
defstruct [
entity_ids: %{}
]
# Utilities
@doc """
"""
@spec new :: t
def new, do: %Structs.EntityReferencesCollection{}
@doc """
Check if an entity of the given type and ID are referenced in the collection.
"""
@spec has_entity?(t, atom, pos_integer) :: t
def has_entity?(entity_references_collection, entity_type, id) do
Enum.member? entity_references_collection[entity_type], id
end
@doc """
Add an entity reference to the collection.
"""
@spec put_entity_id(t, atom, pos_integer) :: t
def put_entity_id(entity_references_collection, entity_type, id) do
entity_references_collection
|> Map.put(
entity_type,
((Map.get(entity_references_collection, entity_type) || []) ++ [ id ])
|> Enum.uniq
)
end
@doc """
Add multiple entity references to the collection.
"""
@spec put_entity_id(t, atom, [ pos_integer ]) :: t
def put_entity_ids(entity_references_collection, entity_type, ids) do
entity_references_collection
|> Map.put(
entity_type,
((Map.get(entity_references_collection, entity_type) || []) ++ ids)
|> Enum.uniq
)
end
@doc """
"""
@spec merge(t | nil, t | nil) :: t
def merge(entity_references_collection1, nil), do: entity_references_collection1
def merge(nil, entity_references_collection2), do: entity_references_collection2
def merge(entity_references_collection1, entity_references_collection2) do
%Structs.EntityReferencesCollection{
entity_ids: Map.merge(
(entity_references_collection1 || %Structs.EntityReferencesCollection{}).entity_ids,
(entity_references_collection2 || %Structs.EntityReferencesCollection{}).entity_ids,
fn _entity_type, entity_ids1, entity_ids2 ->
case { entity_ids1, entity_ids2 } do
{ entity_ids1, entity_ids2 } when is_nil(entity_ids1) and is_nil(entity_ids2) -> nil
{ entity_ids1, entity_ids2 } when is_list(entity_ids1) and is_nil(entity_ids2) -> entity_ids1
{ entity_ids1, entity_ids2 } when is_nil(entity_ids1) and is_list(entity_ids2) -> entity_ids2
{ entity_ids1, entity_ids2 } ->
(entity_ids1 ++ entity_ids2)
|> Enum.uniq
end
end
)
}
end
end