Home > Enterprise >  still collects numbers until get a single number
still collects numbers until get a single number

Time:08-19

I want to create a program using Javascript that converts an alphabet of a string to an ASCII code and collects those numbers until getting a single digit number.

For example: We have this string "Youssef". If we sum their ASCII code we get 782. We must do this operation now,

7   8   2 = 17 => 1   7 => 8 // Now the program will stop.

Thanks in advance

CodePudding user response:

This code gives you an idea of how to deal with spreads and implicit casting in order to help you get to the result.

const str = "Youssef"

let totASCII = [0]

for (let char of str){
    totASCII[0]  = char.charCodeAt(0)
}
totASCII = [...totASCII ""]

while (totASCII.length > 1){
    let intermediate = 0
    totASCII.forEach(item => intermediate  = parseInt(item))
    totASCII = [...intermediate ""]
}

console.log(totASCII "")
  • Related