Created
March 21, 2012 06:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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