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

143
Visualizações
Reduce number of lines in a switch / case with JavaScript

I created a piano, and I have a case for each key. There are 61 of them.

I have a switch case for the keydowns, and for the keyups. So 122 cases !

I show you an exemple for 3 keys :

switch (e.key) {
        // first row white keys
        case '&':
            document.getElementById("1").classList.add("active")
            if (audio1.paused) {
                audio1.play()
            } else {
                audio1.play()
                audio1.currentTime = 0
            }
            break;
        case 'é':
            document.getElementById("2").classList.add("active")
            if (audio2.paused) {
                audio2.play()
            } else {
                audio2.play()
                audio2.currentTime = 0
            }
            break;
        case '"':
            document.getElementById("3").classList.add("active")
            if (audio3.paused) {
                audio3.play()
            } else {
                audio3.play()
                audio3.currentTime = 0
            }
            break;

Here is the link if you want : see the piano

Any idea how I can optimize this ?

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

0

You can create a hash map of the keys to the player ids, something like this:

const elems = {
  '&': '1',
  'é': '2',
  '"': '3',
};

function toggleAudio(e) {
  const id = elems[e.key];
  const player = document.getElementById(id).classList.add('active');
  if (!player.paused) player.currentTime = 0
  player.play()
}
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