How do I check each individual digit within a string?

I was given the challenge of converting a string of digits into 'fake binary' on Codewars.com, and I am to convert each individual digit into a 0 or a 1, if the number is less than 5 it should become a 0, and if it's 5 or over it should become a 1. I know how to analyze the whole string's value like so:

function fakeBin(x){
if (x < 5)
return 0;
else return 1;
}

This however, analyzes the value of the whole string, how would I go about analyzing each individual digit within the string rather than the whole thing?

Note: I have already looked at the solutions on the website and don't understand them, I'm not cheating.

Answers 1

  • The snippet below will take a string and return a new string comprised of zeros and/or ones based on what you described.

    We use a for ...of loop to traverse the input string and will add a 0 or 1 to our return array based on whether the parsed int if greater or less than 5.

    Also note that we are checking and throwing an error if the character is not a number.

    const word = "1639";
    
    const stringToBinary = function(str) {
      let ret = [];
      for (const char of word) {
         if (Number.isNaN(parseInt(char, 10))) {
           throw new Error(`${char} is not a digit!`);
         } else {
           const intVal = parseInt(char, 10);
           ret.push(intVal > 5 ? 1 : 0);
         }
      }
      return ret.join('');
    };
    
    console.log(stringToBinary(word));


Related Articles