Number of letters in the counting JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number, say n. The function should count the letters in the number names from 1 to n.

For example − If n = 5;

Then the numbers are one, two, three, four, five.And the total number of letters are 19, so the output should be 19.

Example

const sumUpto = (num = 1) => {
   let sum = 0;
   const lenHundred = 7;
   const lenThousand = 8;
   const lenPlaceOnes = [0,3,3,5,4,4,3,5,5,4];
   const lenPlaceTens = [0,3,6,6,5,5,5,7,6,6];
   for (let i = 1; i <= num; i++) {
      let placeOnes = i % 10;
      let placeTens = Math.floor(i / 10) % 10;
      let placeHundreds = Math.floor(i / 100) % 10;
      let placeThousands = Math.floor(i / 1000) % 10;
      sum += lenPlaceOnes[placeOnes];
      sum += lenPlaceTens[placeTens];
      if (placeHundreds != 0) {
         sum += lenHundred + lenPlaceOnes[placeHundreds];
      }
      if (placeThousands != 0) {
         sum += lenThousand + lenPlaceOnes[placeThousands];
      }
      if (placeTens === 1) {
         switch (placeOnes) {
            case 4:
            case 6:
            case 7:
            case 9:
            sum += 1;
            break;
         }
      }
      if (i > 100 && i % 100 != 0) {
         sum += 3;
      }
   }
   return sum;
}
console.log(sumUpto(12));
console.log(sumUpto(5));
console.log(sumUpto(122));

Output

This will produce the following output −

51
19
1280
raja
Published on 25-Nov-2020 05:01:25
Advertisements