MapSorter (Map Sorter v0.2.46) View Source

Sorts a list of maps per a list of sort specs.

Also supports:

  • keywords
  • structs implementing the Access behaviour
  • nested maps, keywords or structs implementing the Access behaviour

Link to this section Summary

Functions

Sorts maps per the given sort specs (compile time or runtime).

Link to this section Functions

Link to this macro

sort(maps, sort_specs)

View Source (macro)

Sorts maps per the given sort specs (compile time or runtime).

Examples of sort specs for flat data structures:

- implicit: [:dob, :name]
- mixed:    [:dob, desc: :name]
- explicit: [asc: :dob, desc: :name]

Examples of sort specs with a Date key for flat data structures:

- implicit: [{:dob Date}, :name]
- mixed:    [{:dob Date}, desc: :name]
- explicit: [asc: {:dob Date}, desc: :name]

Examples of sort specs for nested data structures:

- implicit: [[:birth, :date], :name]
- mixed   : [[:birth, :date], desc: :name]
- explicit: [asc: [:birth, :date], desc: :name]

Examples of sort specs with a Date key for nested data structures:

- implicit: [{[:birth, :date], Date}, :name]
- mixed:    [{[:birth, :date], Date}, desc: :name]
- explicit: [asc: {[:birth, :date], Date}, desc: :name]

Examples

iex> require MapSorter
iex> people = [
...>   %{name: "Mike", likes: "movies" , dob: "1992-04-15"},
...>   %{name: "Mary", likes: "travels", dob: "1992-04-15"},
...>   %{name: "Bill", likes: "karate" , dob: "1977-08-28"},
...>   %{name: "Joe" , likes: "boxing" , dob: "1977-08-28"},
...>   %{name: "Jill", likes: "cooking", dob: "1976-09-28"}
...> ]
iex> sort_specs = Tuple.to_list({:dob, {:desc, :likes}})
iex> sorted_people = %{
...>   explicit: MapSorter.sort(people, asc: :dob, desc: :likes),
...>   mixed:    MapSorter.sort(people, [:dob, desc: :likes]),
...>   runtime:  MapSorter.sort(people, sort_specs)
...> }
iex> sorted_people.explicit == sorted_people.mixed and
...> sorted_people.explicit == sorted_people.runtime and
...> sorted_people.explicit
[
  %{name: "Jill", likes: "cooking", dob: "1976-09-28"},
  %{name: "Bill", likes: "karate" , dob: "1977-08-28"},
  %{name: "Joe" , likes: "boxing" , dob: "1977-08-28"},
  %{name: "Mary", likes: "travels", dob: "1992-04-15"},
  %{name: "Mike", likes: "movies" , dob: "1992-04-15"}
]