'alternative to an if else inside a for loop
Currently my code is working properly but I would like to have an alternate version of my code example without the if else. I would like to use functional programming with functions such as find but I am a bit stuck with the second loop inside the first loop.
The aim of the code is to update the array of tasks when either a task or a subTask when their id matches a given id. The updated task (or subTask) should remain at the same position in the array of tasks (or in the array of subTasks)
To simply things:
const idToSearch; let index; let subIndex;
for (const task of tasks){
if (task.id === idToSearch && stuff to validate task){
const task = update(task, parameters);
tasks.splice(index, 1, task);
}
else if (task.hasSubTasks){
for (const subTask of task.subTasks){
if (subTask.id = idToSearch && stuff to validate subtask){
const subTask = update(subTask, parameters);
task.subTasks.splice(subIndex, 1, subTask);
tasks.splice(index,1,task);
return;
}
subIndex++;
}
}
index++;
}
Could you give me some pointers?
Edit: I just reformulated the question, I was not precise enough.
Edit2: the update function is pure. It takes the task (or subTask) and parameters and returns the updated task / subTask.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
