View Source MapSorter.SortSpecs (Map Sorter v0.2.62)
Converts the AST of sort specs into the AST of an Enum.sort/2
compare
function.
Link to this section Summary
Functions
Converts sort_specs
into the AST of an Enum.sort/2
compare function.
Link to this section Types
@type t() :: [MapSorter.SortSpec.t()]
A list of sort specs
Link to this section Functions
Converts sort_specs
into the AST of an Enum.sort/2
compare function.
examples
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
"""
|> String.trim_trailing()
# 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
"""
|> String.trim_trailing()
# 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
"""
|> String.trim_trailing()
# 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}})"}