Last active
June 20, 2024 11:00
-
-
Save erkobridee/29f7f146aaedb78379d2c53eb52ee11c to your computer and use it in GitHub Desktop.
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
// https://jsfiddle.net/erkobridee/56nwr3d2/1/ | |
/* | |
references | |
Digital Root | Math is Fun | |
https://www.mathsisfun.com/numbers/digital-root.html | |
Digital Root Calculator | Omni Calculator | |
https://www.omnicalculator.com/math/digital-root | |
*/ | |
const calcDigitRootOptimized = n => --n % 9 + 1; | |
const calcDigitRoot = n => { | |
if(n === 10) return 1; | |
if(n < 10) return n; | |
return calcDigitRoot((''+n).split('').reduce((acc, d) => acc + Number(d), 0)); | |
} | |
//------------------------------------------------------------------------// | |
// number to string | |
const n2s = value => ''+value; | |
// string to characteres (digits) array | |
const s2a = value => n2s(value).split(''); | |
const showDigitRootCalcSteps = n => { | |
if(n < 10) return n2s(n); | |
const steps = []; | |
let result = n; | |
do { | |
const digitsArray = s2a(result); | |
result = digitsArray.reduce((acc, digit) => acc + Number(digit), 0); | |
steps.push(`( ${digitsArray.join(' + ')} ) = ${result}`) | |
} while( result > 10 ); | |
return `${n} ${steps.join(' ')}`; | |
} | |
//------------------------------------------------------------------------// | |
const inputValue = 9999; | |
const results = { | |
calcDigitRootOptimized: calcDigitRootOptimized(inputValue), | |
calcDigitRoot: calcDigitRoot(inputValue), | |
showDigitRootCalcSteps: showDigitRootCalcSteps(9999) | |
} | |
console.log( | |
`digit root value of ${inputValue} = `, results | |
); | |
/* | |
output: | |
"digit root value of 9999 = ", { | |
calcDigitRoot: 9, | |
calcDigitRootOptimized: 9, | |
showDigitRootCalcSteps: "9999 ( 9 + 9 + 9 + 9 ) = 36 ( 3 + 6 ) = 9" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment