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

116
Visualizações
Looking for a clean function implementation of a switch statement in JavaScript

I am teaching a course that includes explaining functional JavaScript and I want to have a really good example of functional programming that is hopefully cleaner then non-functional. I want to convert the following switch statement to functional. I've made an example of that conversion myself, but hoping there is a simpler solution.

Here is the switch statement version:

let animalType = "Poodle";
switch (animalType) {
  case "Poodle":
  case "Beagle":
  case "Bulldog":
    console.log(animalType + " is a dog.");
    break;
  case "Bengal":
  case "Siamese":
    console.log(animalType + " is a cat.");
    break;
  default:
    console.log(animalType + " is not a dog or cat.");
    break;
}

And here is what I came up with as functional that I'm not that happy about

const result = getAnimalType("Poodle");
console.log("result:" + result)

function getAnimalType(animal) {
  function isDog(animal) {
    const dogs = ["Poodle", "Beagle", "Bulldog"];
    return dogs.includes(animal)
  }
  function isCat(animal) {
    const cats = ["Bengal", "Siamese"];
    return cats.includes(animal)
  }
  return isDog(animal)
    ? animal + " is a dog."
    : isCat(animal)
    ? animal + " is a cat."
    : animal + " is not a dog or cat.";
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use an object to map animal types to functions.

function dog(animalType) {
  return animalType + " is a dog.";
}

function cat(animalType) {
  return animalType + " is a cat.";
}

function other(animalType) {
  return animalType + " is not a dog or cat.";
}

const typeMap = {
  Poodle: dog,
  Beagle: dog,
  Bulldog: dog,
  Bengal: cat,
  Siamese: cat
};

function getAnimalType(animalType) {
  let typeFun = typeMap[animalType] || other;
  return typeFun(animalType);
}

console.log(getAnimalType("Poodle"));

about 4 years ago · Juan Pablo Isaza Relatório

0

One option is an object indexed by dog or cat, whose values are arrays of animal types. This is easily extensible to additional animal types.

const animalNamesByType = {
  dog: ["Poodle", "Beagle", "Bulldog"],
  cat: ["Bengal", "Siamese"]
};
function getAnimalType(animal) {
  const entry = Object.entries(animalNamesByType).find(
    entry => entry[1].includes(animal)
  );
  return entry
  ? `${animal} is a ${entry[0]}`
  : `${animal} is not in animalNamesByType`;
}
console.log(getAnimalType("Poodle"));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can create a really simple 3-line function for this

const dogs = ["Poodle", "Beagle", "Bulldog"];
const cats = ["Bengal", "Siamese"];

const getAnimalType = (animal) => {
  if(dogs.includes(animal)) return `${animal} is a dog`
  if(cats.includes(animal)) return `${animal} is a cat`
  return `${animal} is not a dog or cat.`
}

const result = getAnimalType("Poodle");
console.log("result:" + result)
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