DEV Community

Discussion on: Daily Challenge #264 - Digital Root

Collapse
 
willsmart profile image
willsmart • Edited

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)

knuckle = n =>
  n<10 ? n : knuckle(
    [... ''+n].reduce(
      (acc, char)=>acc + ~~char,
      0
    )
  )

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.

Collapse
 
willsmart profile image
willsmart • Edited

Here's my take on the modulus one, keeping with the nsfw JS syntax theme

muckle = n => n  && (n%9 || 9)