Created
October 23, 2013 19:34
-
-
Save gavinwahl/7125176 to your computer and use it in GitHub Desktop.
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
| 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