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

230
Visualizações
Assertion error on number of digits in a string

My code works for some input but for an input like this: ('This'+ 'painting'+ '1845 and 1910') I get an error: AssertionError 7 == 8. I can solve it using regular expression but I don't know what I'm doing wrong in this. Thanks for answering.

import assert from "assert";

function countDigits(text){
    
    let num = text.split('');
    let sum = 0;
    for (let i=0; i<num.length; i++){
        if (Number(num[i])) {
            sum += 1;}}
    return sum
}

assert.equal(countDigits('This'
 + 'painting'
 + '1845 and 1910'), 8);

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

0

Number(num[i]) will include "0" conversion to a number but in Javascript's if condition, it will be falsy

if(Number("0")) {
  console.log('true') //you're expecting this because it's a number
} else {
  console.log('false') //but in fact, it returns this because 0 is falsy
}

In that case, I'd suggest you use isNaN(num[i])

function countDigits(text) {

  let num = text.split('');
  let sum = 0;
  for (let i = 0; i < num.length; i++) {
    //num[i] = " " will be considered a number, so we need to check it as well
    if (num[i] !== " " && !isNaN(num[i])) {
      sum += 1;
    }
  }
  return sum
}

console.log(countDigits('This' +
  'painting' +
  '1845 and 1910'))

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