Merge pull request #2568 from lebek/optimize-category-lookup
Optimize Finding a Category by Id
This commit is contained in:
commit
1a7eacc70a
|
@ -214,15 +214,18 @@ Discourse.Category.reopenClass({
|
|||
return Discourse.Site.currentProp('sortedCategories');
|
||||
},
|
||||
|
||||
map: function() {
|
||||
return Discourse.Site.currentProp('categoriesById');
|
||||
},
|
||||
|
||||
findSingleBySlug: function(slug) {
|
||||
return Discourse.Category.list().find(function(c) {
|
||||
return Discourse.Category.slugFor(c) === slug;
|
||||
});
|
||||
},
|
||||
|
||||
// TODO: optimise, slow for no real reason
|
||||
findById: function(id){
|
||||
return Discourse.Category.list().findBy('id', id);
|
||||
findById: function(id) {
|
||||
return Discourse.Category.map()[id];
|
||||
},
|
||||
|
||||
findByIds: function(ids){
|
||||
|
|
|
@ -84,16 +84,17 @@ Discourse.Site.reopenClass(Discourse.Singleton, {
|
|||
var result = this._super.apply(this, arguments);
|
||||
|
||||
if (result.categories) {
|
||||
var byId = {};
|
||||
result.categoriesById = {};
|
||||
result.categories = _.map(result.categories, function(c) {
|
||||
byId[c.id] = Discourse.Category.create(c);
|
||||
return byId[c.id];
|
||||
result.categoriesById[c.id] = Discourse.Category.create(c);
|
||||
return result.categoriesById[c.id];
|
||||
});
|
||||
|
||||
// Associate the categories with their parents
|
||||
result.categories.forEach(function (c) {
|
||||
if (c.get('parent_category_id')) {
|
||||
c.set('parentCategory', byId[c.get('parent_category_id')]);
|
||||
c.set('parentCategory',
|
||||
result.categoriesById[c.get('parent_category_id')]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -39,13 +39,14 @@ test('findBySlug', function() {
|
|||
blank(Discourse.Category.findBySlug('luke', 'leia'), 'luke is blank with an incorrect parent');
|
||||
});
|
||||
|
||||
test('findByIds', function(){
|
||||
var categories = [
|
||||
Discourse.Category.create({id: 1}),
|
||||
Discourse.Category.create({id: 2})];
|
||||
test('findByIds', function() {
|
||||
var categories = {
|
||||
1: Discourse.Category.create({id: 1}),
|
||||
2: Discourse.Category.create({id: 2})
|
||||
};
|
||||
|
||||
this.stub(Discourse.Category, 'list').returns(categories);
|
||||
deepEqual(Discourse.Category.findByIds([1,2,3]), categories);
|
||||
this.stub(Discourse.Category, 'map').returns(categories);
|
||||
deepEqual(Discourse.Category.findByIds([1,2,3]), _.values(categories));
|
||||
});
|
||||
|
||||
test('postCountStats', function() {
|
||||
|
|
Loading…
Reference in New Issue