Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Can this be simplified in any way?

if ($('.content').length && (document.referrer.search('page1.html') > 0) ||
    $('.content').length && (document.referrer.search('page2.html') > 0) ||
    $('.content').length && (document.referrer.search('page3.html') > 0) ||
    $('.content').length && (document.referrer.search('page4.html') > 0) ||
    $('.content').length && (document.referrer.search('page5.html') > 0) ||
    $('.content').length && (document.referrer.search('page6.html') > 0) ||
    $('.content').length && (document.referrer.search('page7.html') > 0) ||
    $('.content').length && (document.referrer.search('search/?') > 0)) {
        window.location.href = document.referrer;
};
share|improve this question
4  
It'd help if you can explain what you are doing here. –  hjpotter92 Aug 29 at 13:13

2 Answers 2

up vote 13 down vote accepted

Easily! You can use a regular expression to match page[1-7].html and also search/?:

if ($('.content').length && document.referrer.match(/page[1-7]\.html|search\/\?/)) {
        window.location.href = document.referrer;
};

And never write conditions in such wasteful way:

if (A && B || A && C || A && D) {

when it can be easily simplified to:

if (A && (B || C || D)) {
share|improve this answer
3  
.match(/page[1-7]\.html|search\/\?/) –  hjpotter92 Aug 29 at 13:18
    
Thanks for that, corrected. –  janos Aug 29 at 13:24

The answer of @janos is great for this case, but as a more general answer (and if you want to avoid regular expressions):

If you have logic like this:

(A && B) || (A && C) || (A && D)

Because and and or are distributive, you can rewrite it as:

A && (B || C || D)

And of course you can always extract long repeating code to its own function. If you apply both ideas, you would get:

if ($('.content').length && 
    (search('page1.html') || search('page2.html') || [...] || search('search/?')) {
        window.location.href = document.referrer;
};

function search(page) {
    return document.referrer.search(page) > 0;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.