Skip to content

Instantly share code, notes, and snippets.

@luk3thomas
Last active August 29, 2015 14:14
Show Gist options
  • Save luk3thomas/890b1e25bf057773a45a to your computer and use it in GitHub Desktop.
Save luk3thomas/890b1e25bf057773a45a to your computer and use it in GitHub Desktop.
Crazy sort using eval
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)
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