Skip to content

Instantly share code, notes, and snippets.

@mmun
Last active December 24, 2015 22:39
Show Gist options
  • Save mmun/6873908 to your computer and use it in GitHub Desktop.
Save mmun/6873908 to your computer and use it in GitHub Desktop.
Computed Array Macros
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;
}
});
};
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