Merge pull request #2568 from lebek/optimize-category-lookup

Optimize Finding a Category by Id
This commit is contained in:
Robin Ward 2014-07-23 11:06:54 -04:00
commit 1a7eacc70a
3 changed files with 18 additions and 13 deletions

View File

@ -214,15 +214,18 @@ Discourse.Category.reopenClass({
return Discourse.Site.currentProp('sortedCategories'); return Discourse.Site.currentProp('sortedCategories');
}, },
map: function() {
return Discourse.Site.currentProp('categoriesById');
},
findSingleBySlug: function(slug) { findSingleBySlug: function(slug) {
return Discourse.Category.list().find(function(c) { return Discourse.Category.list().find(function(c) {
return Discourse.Category.slugFor(c) === slug; return Discourse.Category.slugFor(c) === slug;
}); });
}, },
// TODO: optimise, slow for no real reason findById: function(id) {
findById: function(id){ return Discourse.Category.map()[id];
return Discourse.Category.list().findBy('id', id);
}, },
findByIds: function(ids){ findByIds: function(ids){

View File

@ -84,16 +84,17 @@ Discourse.Site.reopenClass(Discourse.Singleton, {
var result = this._super.apply(this, arguments); var result = this._super.apply(this, arguments);
if (result.categories) { if (result.categories) {
var byId = {}; result.categoriesById = {};
result.categories = _.map(result.categories, function(c) { result.categories = _.map(result.categories, function(c) {
byId[c.id] = Discourse.Category.create(c); result.categoriesById[c.id] = Discourse.Category.create(c);
return byId[c.id]; return result.categoriesById[c.id];
}); });
// Associate the categories with their parents // Associate the categories with their parents
result.categories.forEach(function (c) { result.categories.forEach(function (c) {
if (c.get('parent_category_id')) { 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')]);
} }
}); });
} }

View File

@ -39,13 +39,14 @@ test('findBySlug', function() {
blank(Discourse.Category.findBySlug('luke', 'leia'), 'luke is blank with an incorrect parent'); blank(Discourse.Category.findBySlug('luke', 'leia'), 'luke is blank with an incorrect parent');
}); });
test('findByIds', function(){ test('findByIds', function() {
var categories = [ var categories = {
Discourse.Category.create({id: 1}), 1: Discourse.Category.create({id: 1}),
Discourse.Category.create({id: 2})]; 2: Discourse.Category.create({id: 2})
};
this.stub(Discourse.Category, 'list').returns(categories); this.stub(Discourse.Category, 'map').returns(categories);
deepEqual(Discourse.Category.findByIds([1,2,3]), categories); deepEqual(Discourse.Category.findByIds([1,2,3]), _.values(categories));
}); });
test('postCountStats', function() { test('postCountStats', function() {