Reputation: 44351
I have this filter, which I don't like:
var products = this.store.filter('product', function(product) {
var ok = true;
if (compatibility) {
ok = ok && product.compatibility == compatibility;
}
if (format) {
ok = ok && product.format == format;
}
if (priceRange) {
ok = ok && product.priceRange == priceRange;
}
if (productType) {
ok = ok && product.productType == productType;
}
return ok;
});
Basically, the filter function must return true
for products which pass the test, and false
for those which don't pass the test. The filter parameters can have a value of be null
.
What is the more idiomatic way of rewriting the filter function?
Upvotes: 2
Views: 50
Reputation: 324620
For every test that fails, return false;
immediately. There is no point in processing further if you know it's failed.
if( compatibility && product.compatibility != compatibility) {
return false;
}
// ...
return true;
Alternatively, (hint: don't do this!), you could do a really long one-liner:
return (!compatibility || product.compatibility == compatibility) && (!format || product.format == format) // ...
// interestingly this shortcuts just like the "immediately return false" solution
Upvotes: 2