Forgive me if this is too much of a general question but I seem to run into this problem frequently when I need to develop recursive algorithms which update some value on each recursive call. Please take this example bellow:
I want to make a recursive algorithm that accumulates the ages of the given profile and all the kids and kids of kids etc that exist within that profile.
Profile structure:
const profile = { name: 'peter', age: 56, kids: [{ name: 'jill', age: 23, kids: [{ name: 'jeter', age: 1 }, { name: 'bill', age: 2 }] }] }
If I declare a variable outside of the scope of the function and update that it works. Like so:
let totalage = 0 function getAge(profile) { totalage = profile.age + totalage if(!profile.kids) return for(const kid of profile.kids) { getAge(kid) } } getAge( profile) console.log(totalage)
By this logic, to make the function more reusable I want to make a shell function that sets up the age variable so it doesnt have to be globally declared any time I want to get all the ages, but this solution returns 0, the original age value:
function getAges(profile) { let age = 0 recurs( profile, age) return age } function recurs(profile, age) { age = profile.age + age if(!profile.kids) return for(const kid of profile.kids) { recurs(kid, age) } } console.log(getAges(profile))
Any idea what is wrong?
Again, please forgive me if this is a newbie question I'm just trying to learn and improve. Thanks
https://stackoverflow.com/questions/67029881/how-to-use-recursion-to-update-a-locally-scoped-variable April 10, 2021 at 08:59AM
没有评论:
发表评论