2

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);

Hussam
  • 27
  • 4

1 Answers1

1

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'))
Nick Vu
  • 14,512
  • 4
  • 21
  • 31