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

166
Visualizações
refactoring my JavaScript code to remove more then just white space

The following code is functional but I would like to refactor the !== part that allows my ternary to run only on values that are not white space so I can include edge case test's. This would include any non letter value as well as white space and I know that regex may play a part but I can't find a niftty way to incorporate it into the if() statement that precedes the ternary operations.

const letterPositions = function(strPos) {
  if (typeof strPos !== 'string') {
    return console.log('Sorry your input is not a string');
  }

  const result = {};
  for (let i = 0; i < strPos.length; i++) {
    if (strPos[i] !== ' ') {
      result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]);
    }
  }

  return result;
};

console.log(letterPositions('aa bb cc'));

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

0

mainly two options, regex and charcode, welcome to edit if more ways available

const codes = ['A', 'Z', 'a', 'z'].map(x => x.charCodeAt(0))
console.log(codes)

const letterPositions = function(strPos) {
  if (typeof strPos !== 'string') {
    return console.log('Sorry your input is not a string');
  }

  const result = {};
  for (let i = 0; i < strPos.length; i++) {

    //if (strPos[i] !== ' ') {                       // old

    //if (/[A-Za-z]/.test(strPos[i])) {                 // regex

    let code = strPos.charCodeAt(i)
    if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { // charcode
      result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]);
    }
  }

  return result;
};

console.log(letterPositions('aa bb cc'));

about 4 years ago · Juan Pablo Isaza Relatório

0

you can also do that...

const letterPositions = str =>
  {
  if (typeof str !== 'string') 
    return console.log('Sorry your input is not a string' )
 
  return [...str].reduce((r,l,i)=>((l===' ')?null:(r[l]??=[],r[l].push(i)),r),{})
  }

console.log( letterPositions('aa bb cc') )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

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