2

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?

4
  • Well, you could use a helper function that compares multiple properties at once which would be more declarative, or convert it to a simple return false on negative cases which'd make the function just 5 lines long. However, I'd pass the code review as is. Commented Dec 30, 2015 at 20:59
  • if (compatibility && product.compatibility != compatibility) return; Commented Dec 30, 2015 at 21:03
  • What is 'product' doing in filter('product', …)? Commented Dec 30, 2015 at 21:08
  • 1
    @gfullam: that's an Ember method to filter elements from the store. Not really related to the question: I am just interested in the filter itself (the function(product) ... part) Commented Dec 31, 2015 at 10:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

you should maybe put parens around the && expression, even though it doesn't matter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.