i have to sum the numbers like sum of 55555 is 25 and sum 0f 25 is 7 ,but we have to use while loop specifically to solve it?

I have to sum the numbers like sum of 55555 is 25 and sum of 25 is 7, but we have to use while loop specifically to solve it

function createCheckDigit(membershipId) {
    string = membershipId.split('');                
    let sum = 0;                               
    for (var i = 0; i \< string.length; i++) {  
        sum += parseInt(string\[i\],10);         
    }
    return sum \>= 10 ? createCheckDigit(String(sum)) : sum;
}
console.log(createCheckDigit("55555"));

Now i have to do this using while loop. The final answer of the code will be 7 if the number is 55555.

>Solution :

Here is a simple implementation (strings can be iterated like arrays)

function createCheckDigit(membershipId) {
  membershipId = String(membershipId)
  let sum = i = 0

  while (i < membershipId.length) {
    sum += Number(membershipId[i++])
  }

  return (sum >= 10) ? createCheckDigit(sum) : sum
}

console.log(createCheckDigit("55555"))
console.log(createCheckDigit(77777))

Leave a Reply