Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Complexity between if-else, switch and regex

I’m going to optimize javascript code in which I seen old code is like below,

var emcont = $('#emcont').val();
numericMatch = emcont.match(/\d/g);
if (numericMatch == null) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (emcont.length != 14) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (numericMatch.length && numericMatch.length != 10) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else {
    $('#msg_emcont').html('').hide();
}

I going to convert if-else conditions into switch conditions, but the problem in the above code is 2nd condition validation used emcont variable so I can’t directly use numericMatch in switch statement. So I decided used emcont variable directly in the switch statement like the below code,

switch(emcont)
    {
        case emcont.match(/\d/g) == null:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        case emcont.length != 14:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
         case emcont.match(/\d/g).length && emcont.match(/\d/g).length != 10:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        default:
            $('#msg_emcont').html('').hide();
            break;
    }

In used regex in switch case validation, so i need to know which code better in performance wise.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Please do not abuse side effects of switch(true) which is what you meant

This is DRY and easier to read

var emcont = $('#emcont').val();
const numericMatch = emcont.match(/\d/g);
$('#msg_emcont')
  .html(getMessage('msg_emcont'))
  .toggle(
    numericMatch == null || 
    emcont.length != 14  || 
    (numericMatch.length && numericMatch.length != 10)
  )

You might even consider to move

$('#msg_emcont').html(getMessage('msg_emcont'))

to the page load so it is only done once

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading