I’m trying to make a function that calculates the percentage of “completed tasks” in a recursive manner.
Here’s what I have now, but this only calculates the percentage on the parent, not grandparent etc:
const tasks = [
{ id: 1, task: 'Clean apartment', completed: null, parentId: null},
{ id: 2, task: 'Make app', completed: null, parentId: null},
{ id: 3, task: 'Clean bathroom', completed: null, parentId: 1},
{ id: 4, task: 'Clean kitchen', completed: null, parentId: 1},
{ id: 5, task: 'Wash sink', completed: true, parentId: 3},
{ id: 6, task: 'Wash shower', completed: null, parentId: 3},
{ id: 7, task: 'Wash glass panes', completed: null, parentId: 6},
{ id: 8, task: 'Wash floor', completed: null, parentId: 6},
]
function compileTask(tasks, taskId) {
var task = (typeof taskId === 'number') ? tasks.find(task => task.id === taskId) : taskId;
var children = tasks.filter(t => t.parentId === task.id);
task.percent = children.filter(c => c.completed === true).length / children.length * 100
task.children = children.map(child => compileTask(tasks, child));
return task
}
console.log(compileTask(tasks, 1))
As you see, task id 3 is 50% completed because one of the two child tasks are marked completed, but task id 1 is 0% completed. If I’m calculating right in my head, task id 1 should return 25% completed.
Any tips?