Reputation: 182
Basically I have a recursive function to calculate space in certain structures. I want to keep track of 'space' throughout the recursion without the space value resetting on each call. I was previously using a 'space' variable declared outside the function, but it's causing me issues. Is this possible without using a global variable? How?
Current code:
var space = 0;
var fill = function(arr) {
if(arr.length < 1) {
return space;
}
for(let i=0; i<arr.length; i++){
... various conditions and arr manipulation ...
space+=1
}
return fill(arr)
}
example input:
fill([2,4,0,9])
Upvotes: 2
Views: 713
Reputation: 386650
You could take a second parameter for the counting.
var fill = function(array, space = 0) {
if (array.length < 1) return space;
// some code with
space++;
return fill(array, space);
};
Upvotes: 1