Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
Anytime there's this sort of array summarizing is a good time for reduce
Here's a wee JS implementation of the recursive method (didn't know about the modulus one, pretty neat)
So, for numbers greater than ten, convert the number to a string (''+n), split the string into its digits ([... ''+n]), and accumulate the sum of those digits ([... ''+n].reduce((acc, char)=>acc + ~~char, 0). Then recuse another level just in case the sum is multi-digit too.
Note that squiggigle operator~~ (my term, not sure if it's got a name already) reliably converts a value to an signed 32-bit int in a bit less space than doing it properly, it's pretty much the same as the bang bang op !!, just with bitwise negation. It's used here since char is a string, ~~char get's the string's parsed number.
Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
Anytime there's this sort of array summarizing is a good time for
reduceHere's a wee JS implementation of the recursive method (didn't know about the modulus one, pretty neat)
So, for numbers greater than ten, convert the number to a string (
''+n), split the string into its digits ([... ''+n]), and accumulate the sum of those digits ([... ''+n].reduce((acc, char)=>acc + ~~char, 0). Then recuse another level just in case the sum is multi-digit too.Note that squiggigle operator
~~(my term, not sure if it's got a name already) reliably converts a value to an signed 32-bit int in a bit less space than doing it properly, it's pretty much the same as the bang bang op!!, just with bitwise negation. It's used here sincecharis a string,~~charget's the string's parsed number.Here's my take on the modulus one, keeping with the nsfw JS syntax theme