Skip to content

Commit

Permalink
Make SetSort execute functions and compare the return values if given…
Browse files Browse the repository at this point in the history
… a key which returns a function on the objects it sorts.
  • Loading branch information
airhorns committed Mar 5, 2012
1 parent 08a44cb commit 16e51e4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/batman.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/batman.coffee
Expand Up @@ -1421,8 +1421,12 @@ class Batman.SetSort extends Batman.SetProxy
_reIndex: ->
newOrder = @base.toArray().sort (a,b) =>
valueA = $get(a, @key)
if typeof valueA is 'function'
valueA = valueA.call(a)
valueA = valueA.valueOf() if valueA?
valueB = $get(b, @key)
if typeof valueB is 'function'
valueB = valueB.call(b)
valueB = valueB.valueOf() if valueB?
multiple = if @descending then -1 else 1
@compare.call(@, valueA, valueB) * multiple
Expand Down
19 changes: 18 additions & 1 deletion tests/batman/set/set_sort_test.coffee
Expand Up @@ -115,6 +115,24 @@ test "toArray() returns the correct order", ->
expected = [@byFred, @anotherByFred, @byMary, @byZeke]
deepEqual @authorNameSort.toArray(), expected

test "toArray() returns the correct order when sorting on key which returns a function by calling the function", ->
class Test
constructor: (@name) ->
getName: -> @name

a = new Test('a')
b = new Test('b')
c = new Test('c')

base = new Batman.Set(b, a, c)
sorted = base.sortedBy('getName')
deepEqual sorted.toArray(), [a, b, c]

test "toArray() returns the correct order when sorting on the 'valueOf' key to sort primitives", ->
@base = new Batman.Set('b', 'c', 'a')
sorted = @base.sortedBy('valueOf')
deepEqual sorted.toArray(), ['a', 'b', 'c']

test "toArray() includes newly added items in the correct order", ->
@base.add @byJill
expected = [@byFred, @anotherByFred, @byJill, @byMary, @byZeke]
Expand Down Expand Up @@ -163,4 +181,3 @@ test "stopObserving() forgets all observers", ->

@byFred.set('author', @mary)
deepEqual @authorNameSort.toArray(), expected

0 comments on commit 16e51e4

Please sign in to comment.