Enumex.Static.Components.Sort behaviour (Enumex v1.0.0)

View Source

A component that provides comparison functionality for sorting enum values based on their index, ensuring consistent sorting across your application.

The comparison logic is required by Elixir's Enum.sort/2 function. It enables sorting enum values regardless of their representation (id, index, or struct), making it easy to order enum values in your application.

Example

defmodule MyApp.Enums do
  use Enumex.Static, components: [Enumex.Static.Components.Sort]
end

Summary

Callbacks

Compares two enum values and returns their relationship.

Callbacks

compare(arg1, arg2)

@callback compare(
  Enumex.Value.id() | Enumex.Value.index() | Enumex.Value.t(),
  Enumex.Value.id() | Enumex.Value.index() | Enumex.Value.t()
) :: :lt | :eq | :gt

Compares two enum values and returns their relationship.

Return value

:lt

when the first value is less than the second

  iex> first_value = Enumex.Value.new(MyApp.Enums, :my_enum, :first, 1)
  iex> second_value = Enumex.Value.new(MyApp.Enums, :my_enum, :second, 2)
  iex> MyApp.Enums.compare(first_value, second_value)
  :lt
  iex> MyApp.Enums.compare(first_value, :second)
  :lt
  iex> MyApp.Enums.compare(first_value, 2)
  :lt
  iex> MyApp.Enums.compare(:first, second_value)
  :lt
  iex> MyApp.Enums.compare(:first, :second)
  :lt
  iex> MyApp.Enums.compare(:first, 2)
  :lt
  iex> MyApp.Enums.compare(1, second_value)
  :lt
  iex> MyApp.Enums.compare(1, :second)
  :lt
  iex> MyApp.Enums.compare(1, 2)
  :lt

:eq

when the values are equal

  iex> first_value = Enumex.Value.new(MyApp.Enums, :my_enum, :first, 1)
  iex> MyApp.Enums.compare(first_value, first_value)
  :eq
  iex> MyApp.Enums.compare(first_value, :first)
  :eq
  iex> MyApp.Enums.compare(first_value, 1)
  :eq
  iex> MyApp.Enums.compare(:first, first_value)
  :eq
  iex> MyApp.Enums.compare(:first, :first)
  :eq
  iex> MyApp.Enums.compare(:first, 1)
  :eq
  iex> MyApp.Enums.compare(1, first_value)
  :eq
  iex> MyApp.Enums.compare(1, :first)
  :eq
  iex> MyApp.Enums.compare(1, 1)
  :eq

:gt

when the first value is greater than the second

  iex> first_value = Enumex.Value.new(MyApp.Enums, :my_enum, :first, 1)
  iex> second_value = Enumex.Value.new(MyApp.Enums, :my_enum, :second, 2)
  iex> MyApp.Enums.compare(second_value, first_value)
  :gt
  iex> MyApp.Enums.compare(second_value, :first)
  :gt
  iex> MyApp.Enums.compare(second_value, 1)
  :gt
  iex> MyApp.Enums.compare(:second, first_value)
  :gt
  iex> MyApp.Enums.compare(:second, :first)
  :gt
  iex> MyApp.Enums.compare(:second, 1)
  :gt
  iex> MyApp.Enums.compare(2, first_value)
  :gt
  iex> MyApp.Enums.compare(2, :first)
  :gt
  iex> MyApp.Enums.compare(2, 1)
  :gt