I had a collection that I'm filtering in an EmberJS component. It's filtering by country, fulfilled, and mood. Each filter also has an all
value which disables that filter.
export default Ember.Component.extend({
markersByMood: function(){
if(this.get('selectedMood') === 'all'){
return this.get('markers');
}
return this.get('markers'.filterBy('properties.mood', this.get('selectedMood')));
}.property('markers.[]', 'selectMood'),
markersByCountry: function(){
if(this.get('selectedCountry') === 'all'){
return this.get('markers');
}
return this.get('markers'.filterBy('properties.country', this.get('selectedCountry')));
}.property('markers.[]', 'selectCountry'),
markersByFulfilled: function(){
if(this.get('selectedFulfilled') === 'all'){
return this.get('markers');
}
return this.get('markers'.filterBy('properties.fulfilled', this.get('selectedFulfilled')));
}.property('markers.[]', 'selectedFulfilled'),
filteredMarkers: Ember.computed.union("markersByMood", "markersByCountry", "markersByFulfilled")
});
The 3 filters repeat the same basic logic. How would you apply DRY to this?
1 Answer 1
First, fix the syntax, so that you don't get a string has no method filterBy
error:
return this.get('markers'.filterBy('properties.mood', this.get('selectedMood')));
becomes
return this.get('markers').filterBy('properties.mood', this.get('selectedMood'));
Next, while using Ember, one tends to think in terms of complicated things like computed properties but forgets that basic JavaScript is available. The best way to DRY here is to just use a function!
export default Ember.Component.extend({
markersByMood: function(){
return markersByProp(this.get('markers'), 'properties.mood', this.get('selectedMood'));
}.property('markers.[]', 'selectMood'),
markersByCountry: function(){
return markersByProp(this.get('markers'), 'properties.country', this.get('selectedCountry'));
}.property('markers.[]', 'selectCountry'),
markersByFulfilled: function(){
return markersByProp(this.get('markers'), 'properties.fulfilled', this.get('selectedFulfilled'));
}.property('markers.[]', 'selectedFulfilled'),
filteredMarkers: Ember.computed.union("markersByMood", "markersByCountry", "markersByFulfilled")
});
function markersByProp(collection, filterProp, selection) {
if (selection === "all") {
return collection;
}
return collection.filterBy(filterProp, selection);
}
The markersByProp
function above encapsulates the common functionality of the three computed properties.
Note that my above solution also avoids calling this.get('markers')
extra times by passing the result into the function.
-
1\$\begingroup\$ Hi! Welcome to Code Review. Please explain your though process towards your final code, so that OP can learn from this. \$\endgroup\$TheCoffeeCup– TheCoffeeCup2015年12月23日 23:48:09 +00:00Commented Dec 23, 2015 at 23:48
-
\$\begingroup\$ Thanks, TheCoffeeCup. I've edited my answer to expand on my thinking. \$\endgroup\$Gaurav– Gaurav2015年12月24日 01:48:00 +00:00Commented Dec 24, 2015 at 1:48