Last active
December 24, 2015 22:39
-
-
Save mmun/6873908 to your computer and use it in GitHub Desktop.
Computed Array Macros
This file contains hidden or 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
Ember.computed.groupBy = function(dependentKey, propertyKey) { | |
return Ember.reduceComputed(dependentKey + ".@each." + propertyKey, { | |
initialValue: Ember.MapWithDefault.create({ | |
defaultValue: function() { | |
return Ember.Set.create(); | |
} | |
}), | |
addedItem: function(groups, item, changeMeta) { | |
var groupValue = item.get(propertyKey), | |
group = groups.get(groupValue); | |
group.add(item); | |
return groups; | |
}, | |
removedItem: function(groups, item, changeMeta) { | |
var groupValue = changeMeta.previousValues[propertyKey], | |
group = groups.get(groupValue); | |
group.remove(item); | |
if (Ember.isEmpty(group)) { | |
groups.remove(group); | |
} | |
return groups; | |
} | |
}); | |
}; |
This file contains hidden or 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
Ember.computed.take = function(dependentKey, limit) { | |
return Ember.arrayComputed(dependentKey, { | |
addedItem: function(array, item, changeMeta, instanceMeta) { | |
if (changeMeta.index < limit) { | |
array.insertAt(changeMeta.index, item); | |
} | |
if (array.get('length') > limit) { | |
array.popObject(); | |
} | |
return array; | |
}, | |
removedItem: function(array, item, changeMeta, instanceMeta) { | |
if (changeMeta.index < limit) { | |
array.removeAt(changeMeta.index, 1); | |
} | |
if (changeMeta.arrayChanged.get('length') > limit) { | |
array.insertAt(limit - 1, changeMeta.arrayChanged.objectAt(limit)); | |
} | |
return array; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment