I am trying to get the sum of tasks completed using recursion. An object represents a team member and they can manage other members.
var team = {
name: 'Rufus',
completedTasks: 4,
manages: [
{
name: 'Clara',
completedTasks: 6,
manages: [
{
name: 'Dana',
completedTasks: 12,
manages: []
}
]
},
{
name: 'Charles',
completedTasks: 19,
manages: []
}
]
};
This is what I have implemented, but I am not getting 41. 4 + 6 + 12 + 19 = 41. The function is returning 45.
var totalTasks = function (team) {
var sum = 0;
var innerFunction = function(obj) {
if (obj.manages.length === 0) {
sum += obj.completedTasks;
return;
}
obj.manages.forEach(function(item) {
sum += obj.completedTasks;
innerFunction(item);
});
};
innerFunction(team);
return sum;
};
totalTasks(team);