Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
What alternative can be used instead of if / else statements to make the code work in the same way?

Im trying to find way to make the code work the same way shown in the code below using the other methods to if/else statements. Can anyone help me with that? I have a lot more cities and clearly this isn't going to scale.

function getCityNameFromURL() {
    var curURL = "" + Request.ServerVariables("URL");
    var returnCityName = "";
    curURL = curURL.toLowerCase();

    if (curURL.indexOf("/sgncp/") != -1 || curURL.indexOf("/mlgct/") != -1)
        returnCityName = "London";
    if (
        curURL.indexOf("/berlinplus/") != -1 ||
        curURL.indexOf("/berlinadmin/") != -1
    )
        returnCityName = "Berlin";
    else if (
        curURL.indexOf("/tokyoplus/") != -1 ||
        curURL.indexOf("/tokyoadmin/") != -1
    )
        returnCityName = "Tokyo";
    else if (
        curURL.indexOf("/parisplus/") != -1 ||
        curURL.indexOf("/parisadmin/") != -1
    )
        returnCityName = "Paris";

    return returnCityName;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

How about a more simple configuration based code? You could even move the city mapping info in to a separate resource.

This would allow simpler updates without having to write extra code.

function getCityNameFromURL() {
    var curURL = "" + Request.ServerVariables("URL");
    curURL = curURL.toLowerCase();

    var cityMappings = [
        { code: '/sgncp/', city: 'London' },
        { code: '/mlgct/', city: 'London' },
        { code: '/berlinplus/', city: 'Berlin' },
        { code: '/berlinadmin/', city: 'Berlin' },
        { code: '/tokyoplus/', city: 'Tokyo' },
        { code: '/tokyoadmin/', city: 'Tokyo' },
        { code: '/parisplus/', city: 'Paris' },
        { code: '/parisadmin/', city: 'Paris' }
    ];

    return cityMappings
        .find(mapping => curURL.indexOf(mapping.code) >= 0)
        ?.city ?? '';
}

Note also, the null-conditional ?. when attempting to access the city property just incase the URL doesn't match any of them and returns an empty string.

Version with for loop

Replace the cityMappings.find code with this

    for (let i = 0; i < cityMappings.length; i++){
        const mapping = cityMappings[i];
        if (curURL.indexOf(mapping.code) >= 0)
            return mapping.city;
    }

    // in case no match was found return an emtpy string.
    return '';
about 4 years ago · Juan Pablo Isaza Relatório

0

This answer is very similar to the one already given by phuzi.

This answer also introduces a city mapping, but in a somewhat different manner to reduce string duplication. I've also introduced a defaultCity variable to (arguably) improve code readability.

function getCityNameFromURL() {
  const curURL = ("" + Request.ServerVariables("URL")).toLowerCase();

  const defaultCity = { name: "" };
  const cities = [
    { name: "London", patterns: ["/sgncp/",      "/mlgct/"      ] },
    { name: "Berlin", patterns: ["/berlinplus/", "/berlinadmin/"] },
    { name: "Tokyo",  patterns: ["/tokyoplus/",  "/tokyoadmin/" ] },
    { name: "Paris",  patterns: ["/parisplus/",  "/parisadmin/" ] },
  ];

  const city = cities.find(({ patterns }) => (
    patterns.some(pattern => curURL.includes(pattern))
  )) || defaultCity;

  return city.name;
}

Or if you prefer a for-loop:

for (const { name, patterns } of cities) {
  for (const pattern of patterns) {
    if (curURL.includes(pattern)) return name;
  }
}

return "";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda