[SOLVED] Complexity between if-else, switch and regex

Issue

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.

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

Answered By – mplungjan

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *