View Source MapSorter.SortSpecs (Map Sorter v0.2.66)

Converts the AST of sort specs into the AST of an Enum.sort/2 compare function.

Summary

Types

t()

A list of sort specs

Functions

Converts sort_specs into the AST of an Enum.sort/2 compare function.

Types

@type t() :: [MapSorter.SortSpec.t()]

A list of sort specs

Functions

@spec to_quoted(t() | Macro.t()) :: {:ok, Macro.t()} | {:error, Macro.t()}

Converts sort_specs into the AST of an Enum.sort/2 compare function.

Examples

# Compile time sort specs...
iex> alias MapSorter.SortSpecs
iex> sort_specs = [:dob]
iex> {:ok, comp_fun_ast} = SortSpecs.to_quoted(sort_specs)
iex> {:&, _meta, [args]} = comp_fun_ast
iex> {comp_fun, []} = Code.eval_quoted(comp_fun_ast)
iex> is_function(comp_fun, 2) and Macro.to_string(args)
"""
cond do
  &1[:dob] < &2[:dob] -> true
  &1[:dob] > &2[:dob] -> false
  true -> true or &1 * &2
end\
"""

# Compile time sort specs...
iex> alias MapSorter.SortSpecs
iex> sort_specs = fn -> [desc: :dob, asc: :bmi] end
iex> {:ok, comp_fun_ast} = sort_specs.() |> SortSpecs.to_quoted()
iex> {:&, _meta, [args]} = comp_fun_ast
iex> {comp_fun, []} = Code.eval_quoted(comp_fun_ast)
iex> is_function(comp_fun, 2) and Macro.to_string(args)
"""
cond do
  &1[:dob] > &2[:dob] -> true
  &1[:dob] < &2[:dob] -> false
  &1[:bmi] < &2[:bmi] -> true
  &1[:bmi] > &2[:bmi] -> false
  true -> true or &1 * &2
end\
"""

# Compile time sort specs...
iex> alias MapSorter.SortSpecs
iex> sort_specs = [:dob, desc: :likes]
iex> {:ok, comp_fun_ast} = SortSpecs.to_quoted(sort_specs)
iex> {:&, _meta, [args]} = comp_fun_ast
iex> {comp_fun, []} = Code.eval_quoted(comp_fun_ast)
iex> is_function(comp_fun, 2) and Macro.to_string(args)
"""
cond do
  &1[:dob] < &2[:dob] -> true
  &1[:dob] > &2[:dob] -> false
  &1[:likes] > &2[:likes] -> true
  &1[:likes] < &2[:likes] -> false
  true -> true or &1 * &2
end\
"""

# Runtime sort specs...
iex> alias MapSorter.SortSpecs
iex> sort_specs = quote do: Tuple.to_list({:dob, {:desc, :likes}})
iex> {:ok, comp_fun_ast} = SortSpecs.to_quoted(sort_specs)
iex> {{:., _, nested_args}, _meta, [args]} = comp_fun_ast
iex> {comp_fun, []} = Code.eval_quoted(comp_fun_ast)
iex> is_function(comp_fun, 2) and
...> {Macro.to_string(nested_args), Macro.to_string(args)}
{"[MapSorter.Compare, :fun]", "Tuple.to_list({:dob, {:desc, :likes}})"}