View Source MultiSort (MultiSort v0.1.0)

Documentation for MultiSort.

Summary

Functions

Sort an enum according to a priortized list of comparators. Inspired by Ecto/SQL order by.

Types

@type comparator() ::
  {order(), map_fn()}
  | {order(), map_fn(), compare_fn()}
  | {order(), map_fn(), module()}
  | {order(), map_fn(), list()}
@type compare_fn() :: (any(), any() -> :eq | :lt | :gt)
@type map_fn() :: (any() -> any())
@type order() :: :asc | :desc

Functions

@spec by(Enum.t(), [comparator()]) :: list()

Sort an enum according to a priortized list of comparators. Inspired by Ecto/SQL order by.

Sort posts first by title and then by descending date:

posts
|> MultiSort.by([
    {:asc, &1.title}
    # Pass Date module as third element because we need to use Date.compare/2 to compare dates
    {:desc, &1.date, Date},
])

Sort posts first by category according to order list and then by title:

post_category_order = [:business, :sports, :politics]
posts
|> MultiSort.by([
    {:asc, &1.category, post_category_order},
    {:asc, &1.title}
])

The third element of the tuple can either be:

  • Left out entirely, resuting in the default elixir comparison
  • Be a module with a compare/2 function
  • Be a function that takes 2 arguemnts and returns :eq, :lt, or :gt
  • Be a list that describes sort order
Link to this function

compound_comparator(comparators)

View Source