Created
August 13, 2021 21:19
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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