Last active
August 29, 2015 14:14
-
-
Save luk3thomas/890b1e25bf057773a45a to your computer and use it in GitHub Desktop.
Crazy sort using eval
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
describe "#sortBy", -> | |
it "sorts on simple props", -> | |
sorted = [ {name: "bar"}, {name: "baz"}, {name: "foo"} ] | |
unsorted = [ {name: "foo"}, {name: "bar"}, {name: "baz"} ] | |
expect(unsorted.sort(sortBy("name"))).toEqual(sorted) | |
it "sorts in nested objects", -> | |
unsorted = [ {name: first: "foo"}, {name: first: "bar"}, {name: first: "baz"} ] | |
sorted = [ {name: first: "bar"}, {name: first: "baz"}, {name: first: "foo"} ] | |
expect(unsorted.sort(sortBy("name.first"))).toEqual(sorted) | |
it "sorts by function output", -> | |
foo = -> "foo" | |
bar = -> "bar" | |
baz = -> "baz" | |
unsorted = [ {name: foo}, {name: bar}, {name: baz} ] | |
sorted = [ {name: bar}, {name: baz}, {name: foo} ] | |
expect(unsorted.sort(sortBy("name()"))).toEqual(sorted) |
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
sortBy: (prop) -> | |
(a, b) -> | |
if eval("a.#{prop} > b.#{prop}") | |
1 | |
else if eval("a.#{prop} < b.#{prop}") | |
-1 | |
else | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment