From c044f18bcdda4aad995f622b818524c8fbf0a7b5 Mon Sep 17 00:00:00 2001 From: CJ Kihlbom Date: Sun, 18 Mar 2012 14:34:17 -0700 Subject: [PATCH] Add Collection#sortBy method Sorts the collection by the given attribute of each item. Collection#sortBy will trigger a 'update' event on the collection, making views update automatically. Example: @collection = new Serenade.Collection([{name:'Jonas'}, {name:'CJ'}]) @collection.sortBy('name') @collection.get(0) # Returns the `{name:'CJ'}` object --- spec/collection.spec.coffee | 12 ++++++++++++ src/collection.coffee | 2 ++ 2 files changed, 14 insertions(+) diff --git a/spec/collection.spec.coffee b/spec/collection.spec.coffee index 56beed1..9d45129 100644 --- a/spec/collection.spec.coffee +++ b/spec/collection.spec.coffee @@ -42,6 +42,18 @@ describe 'Serenade.Collection', -> @collection.sort() expect(@collection).toHaveReceivedEvent('update') + describe '#sortBy', -> + it 'updates the order of the items in the collection', -> + item1 = {name: 'CJ', age: 30} + item2 = {name: 'Anders', age: 37} + @collection.update([item1, item2]) + + @collection.sortBy('age') + expect(@collection.list).toEqual([item1, item2]) + + @collection.sortBy('name') + expect(@collection.list).toEqual([item2, item1]) + describe '#push', -> it 'adds an item to the collection', -> @collection.push('g') diff --git a/src/collection.coffee b/src/collection.coffee index 08e02da..1c10b8f 100644 --- a/src/collection.coffee +++ b/src/collection.coffee @@ -28,6 +28,8 @@ class exports.Collection sort: (fun) -> @list.sort(fun) @trigger("update", @list) + sortBy: (attribute) -> + @sort((a, b) -> if a[attribute] < b[attribute] then -1 else 1) forEach: (fun) -> forEach(@list, fun) map: (fun) ->