Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda