I have a question about initializing a variable as a global versus local variable. I got different results for variable sum as a global variable (output: 16) versus sum as a local variable inside helper function dfs (output: 10). Does it have something to do with recursive nature?
I am calculating sum as the running total of each integer multiply by its depth in the nested array.
The test case is [[1,1],2,[1,1]] The correct answer for the sum is 10.
Why does the first method, declaring a global variable, is wrong in this case? What is the best practice?
//global variable
let sum = 0
function dfs(nestedList, depth){
for(let i=0; i<nestedList.length; i++){
if(nestedList[i].isInteger()) {
sum += nestedList[i].getInteger()*depth
}
else {
sum += dfs(nestedList[i].getList(),depth+1)
}
}
return sum
}
var depthSum = function(nestedList) {
console.log(sum)
return dfs(nestedList,1)
};
local variable
function dfs(nestedList, depth){
let sum = 0
for(let i=0; i<nestedList.length; i++){
if(nestedList[i].isInteger()) {
sum += nestedList[i].getInteger()*depth
}
else {
sum += dfs(nestedList[i].getList(),depth+1)
}
}
return sum
}
var depthSum = function(nestedList) {
console.log(sum)
return dfs(nestedList,1)
};
Recursion is a functional heritage and so using it with functional style typically yields the best results. Below we see dfs
as a pure expression. Concerns about global scope, intermediate state, and side effects disappear!
const dfs = (t = [], d = 0) =>
Array.isArray(t)
? t.reduce((r, v) => r + dfs(v, d + 1), 0)
: t * d
console.log(dfs([[1,1],2,[1,1]]))
// (1*2 + 1*2 + 2*1 + 1*2 + 1*2)
// 10
console.log(dfs([1,[2,[3,[4]]]]))
// (1*1 + 2*2 + 3*3 + 4*4)
// 30