Skip to content

Instantly share code, notes, and snippets.

@jrus
Created March 21, 2012 06:08
Show Gist options
  • Save jrus/2145082 to your computer and use it in GitHub Desktop.
Save jrus/2145082 to your computer and use it in GitHub Desktop.
sort a javascript array using a decorate-sort-undecorate pattern; especially useful if the sort comparison is expensive to compute
# Accepts a list and a key function to apply to each item,
# and then uses a decorate-sort-undecorate pattern to actually
# do the sorting. Returns a new list. Keeps track of the index
# to make sure the sort is stable.
sort_by = (list, key) ->
cmp = ({key: k_a, index: i_a}, {key: k_b, index: i_b}) ->
if k_a == k_b then i_a - i_b else if k_a < k_b then -1 else 1
decorated = ({item, index, key: key item} for item, index in list)
item for {item} in decorated.sort cmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment