Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created October 23, 2013 19:34
Show Gist options
  • Select an option

  • Save gavinwahl/7125176 to your computer and use it in GitHub Desktop.

Select an option

Save gavinwahl/7125176 to your computer and use it in GitHub Desktop.
var group_reduce = function (dependentKey, key_func, reduce) {
return Ember.reduceComputed.call(null, dependentKey, {
initialValue: Ember.A,
initialize: function(initialValue, changeMeta, instanceMeta) {
instanceMeta.meta = new Ember.Map();
},
addedItem: function (accumulatedValue, obj, changeMeta, instanceMeta) {
var key = key_func(obj), reduced_object;
if (instanceMeta.meta.get(key) === undefined) {
instanceMeta.meta.set(key, {items: Ember.A(), index: accumulatedValue.get('length')});
}
instanceMeta.meta.get(key).items.push(obj);
reduced_object = reduce(key, instanceMeta.meta.get(key).items);
accumulatedValue.replace(instanceMeta.meta.get(key).index, 1, [reduced_object]);
return accumulatedValue;
},
removedItem: function (accumulatedValue, obj, changeMeta, instanceMeta) {
var key = null, keyfound = false, index;
instanceMeta.meta.forEach(function(i, val) {
if (val.items.contains(obj)) {
key = i;
keyfound = true;
}
});
if ( ! keyfound )
throw new Error("You just asked me to remove an object " +
"that's not in instanceMeta");
index = instanceMeta.meta.get(key).index;
instanceMeta.meta.get(key).items.removeAt(
instanceMeta.meta.get(key).items.indexOf(obj));
if (instanceMeta.meta.get(key).items.length == 0) {
accumulatedValue.removeAt(index);
instanceMeta.meta.forEach(function(i, val) {
if (val.index > index)
val.index--;
});
instanceMeta.meta.remove(key)
}
else {
accumulatedValue.replace(index, 1,
[reduce(key, instanceMeta.meta.get(key).items)]
);
}
return accumulatedValue;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment