Reputation: 1004
I want to recursively sum an integer: to split an integer into an array and then sum the individual items until I am left with a single integer array.
This is my logic:
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
let digits = (""+result).split("").map(Number);
}
return digits;
};
This is the error code my Node.js chucks at me (at line 4 in the example code above):
ReferenceError: digits is not defined
at digital_root (repl:6:18)
I'm assuming that the variable digits
is accessible inside the scope of the while loop, but obviously, I seem to be wrong? Could someone shed some insight here for me, please?
EDIT: Thank you everyone for your help! I've solved the issue.
For your curiosity, this is the mathematical form underlying my algorithm:
http://mathworld.wolfram.com/DigitalRoot.html
It could also have been solved in one line:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
Upvotes: 3
Views: 1468
Reputation: 4557
Don't set digits
in that manner, the digits
inside of the loop should not have let
in front of it because you have already defined digits
outside the loop.
This will give you the result you expect:
digital_root = n => (Array.from(`${n}`)).reduce((sum, val) => sum + ~~val, 0);
console.log(digital_root(12345));
Hope this helps,
Upvotes: 2
Reputation: 10975
Issue is let keyword, as let has block level scope, "digits" is not defined at the start of the while loop
Removing let for digits in while loop
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
digits = (""+result).split("").map(Number);
}
return digits;
}
console.log(digital_root(47))
Upvotes: 2
Reputation: 413
The inner let for digits (line 5) should be removed
function digital_root(n) {
let digits = (""+n).split("").map(Number);
while (digits.length > 1) {
let result = digits.reduce((sum, int) => sum + int);
digits = (""+result).split("").map(Number);
}
return digits;
}
Upvotes: 2