Forked from danmartens/ember.array_extensions.js.coffee
Created
March 21, 2014 17:41
-
-
Save RohitRox/9691567 to your computer and use it in GitHub Desktop.
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
# Sorts an array based on a property of each object within the array | |
# | |
# Examples: | |
# | |
# [Em.Object.create(a: 1), Em.Object.create(a: 5), Em.Object.create(a: 3)].sortProperty('a') | |
# > [{a: 1}, {a: 3}, {a: 5}] | |
# | |
# As a computed property: | |
# | |
# AC = Em.ArrayController.extend | |
# content: [Em.Object.create(a: 1), Em.Object.create(a: 5), Em.Object.create(a: 3)] | |
# sorted: (-> @content.sortProperty('a')).property('content.@each.a') | |
Array::sortProperty = (property, order = 'DESC') -> | |
if order == 'DESC' | |
return @sort (a, b) => | |
if a.get(property) > b.get(property) then 1 | |
else if a.get(property) < b.get(property) then -1 | |
else 0 | |
else if order == 'ASC' | |
return @sort (a, b) => | |
if a.get(property) < b.get(property) then 1 | |
else if a.get(property) > b.get(property) then -1 | |
else 0 | |
else throw new Error('Sort order must be DESC or ASC.') | |
Array::maxObject = (property) -> | |
max = @objectAt(0) | |
@forEach (o) -> max = o if o.get(property) > max.get(property) | |
return max | |
Array::maxValue = (property) -> | |
@maxObject(property).get(property) | |
Array::minObject = (property) -> | |
min = @objectAt(0) | |
@forEach (o) -> min = o if o.get(property) < min.get(property) | |
return min | |
Array::minValue = (property) -> | |
@minObject(property).get(property) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment