Skip to content

Instantly share code, notes, and snippets.

@Asherlc
Last active May 23, 2016 17:49
Show Gist options
  • Save Asherlc/e28bc2b4ebb257bb8b940439ded07506 to your computer and use it in GitHub Desktop.
Save Asherlc/e28bc2b4ebb257bb8b940439ded07506 to your computer and use it in GitHub Desktop.
import Ember from 'ember';
import DS from 'ember-data';
const {
A,
Helper,
computed,
defineProperty,
get,
observer,
set,
isPresent
} = Ember;
const groupFunction = function() {
const groups = new A();
const items = get(this, 'array');
const property = get(this, 'byPath');
const promises = items.map(function(item) {
const value = get(item, property);
return Promise.resolve(value).then((resolvedValue) => {
let group = groups.findBy(property, resolvedValue);
if (isPresent(group)) {
get(group, 'items').push(item);
} else {
group = { [property]: resolvedValue, items: [item] };
groups.push(group);
}
});
});
return DS.PromiseArray.create({
promise: Promise.all(promises).then(() => { return groups; })
});
};
export default Helper.extend({
compute([byPath, array]) {
set(this, 'array', array);
set(this, 'byPath', byPath);
return get(this, 'content');
},
byPathDidChange: observer('byPath', function() {
let byPath = get(this, 'byPath');
if (byPath) {
defineProperty(this, 'content', computed(`array.@each.${byPath}`, groupFunction));
} else {
defineProperty(this, 'content', null);
}
}),
contentDidChange: observer('content', function() {
this.recompute();
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment