Skip to content

Instantly share code, notes, and snippets.

@skcorroh
Created August 13, 2021 21:19
Show Gist options
  • Save skcorroh/e4b0162718d7320d61a5b4f778605e17 to your computer and use it in GitHub Desktop.
Save skcorroh/e4b0162718d7320d61a5b4f778605e17 to your computer and use it in GitHub Desktop.
During a code challenge I was tasked creating a function (details after) and tried to do it recursively, I had to change gears but to prove to myself that I could do it, here it is. ~Challenge: "Write a function numericReduction(number) that takes a number and adds the digits together until only 1 digit remains and return the number of itteratio…
function numericReduction(num, count=1) {
if(isNaN(num)) throw new Error('num must be a valid integer')
var new_num = (num+'').split('').reduce((total, value)=>total+=parseInt(value),0)
if (new_num >= 10) {
return numericReduction(new_num, count + 1)
} else {
return count;
}
}
numericReduction(99) // 99 → 18 → 9 : returns 2
numericReduction(101) // 101 → 2 : returns 1
numericReduction(199) // 199 → 19 → 10 → 1 : returns 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment