0
\$\begingroup\$

I have a jQuery script that checks for the strength of a password. The code looks like this (with more more of those "blocks"):

if(passwordLC && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else


if(passwordUC && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else

if(passwordN && lessThan12Password)
{
    $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show();
    $('.passwordStrenght').css('background-color',red);
    $('#password').css('border-color',green);
    $('.passwordStrenghtInfo').text(weak).show();
    passwordErrors = true;
}else

And it goes on and on...

Is there a way to reduce all that code to something simpler and efficient, or am I stuck with those horrible "blocks" of repeated code?

\$\endgroup\$
2
\$\begingroup\$

The solution depends on your exact requirements and the context. In your case, you could simplify the if-condition like below. If all fit into one if, you can write your code block there only once. If you need it and can't unify your condition, make it a function.

Here, I'm using a combined approach. I put the code from your if into a function, jQuery objects are cached and don't have to be recreated (but are still protected from outside modification because they only exist inside the scope of that function). And I combined all the conditions I could see in your example.

var indicateBadPassword = (function() {
        var $passwordStrength = $('.passwordStrength'),
            $password = $('#password'),
            $passwordStrengthInfo = $('.passwordStrenghtInfo');
        return function() {
            $passwordStrength.
                animate({width:'75px',height:'5px'},200).
                show().
                css('background-color',red);
            $password.css('border-color',green);
            $passwordStrengthInfo.text(weak).show();
            passwordErrors = true;

        }
    })();
if (lessThan12Password && (passwordLC || passwordUC || passwordN)) {
    indicateBadPassword();
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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