Test name | Executions per second |
---|---|
recursion | 62710.5 Ops/sec |
iterative | 83154.1 Ops/sec |
<!--your preparation HTML code goes here-->
var myTasks = [];
myCopy = null;
function flattenTasks(tasks, flattenContacts = false){
let flattened = [];
tasks.forEach(task => {
if (flattenContacts) {
flattened.push(
{
task,
'contacts': task?.contacts?.length ? task.contacts.map(c => c.id) : [],
'subtasks': task?.subtasks?.length ? task.subtasks.map(s => s.id_uuid) : [],
}
)
} else {
flattened.push(
{
task,
'subtasks': task?.subtasks?.length ? task.subtasks.map(s => s.id_uuid) : [],
}
)
}
if (task?.subtasks?.length) {
flattened = [flattened, flattenTasks(task.subtasks, flattenContacts)];
}
})
return flattened;
}
myCopy = flattenTasks(myTasks);
function flattenTasks(tasks) {
const result = [];
const stack = [tasks];
while (stack.length) {
const task = stack.pop();
result.push({ task });
if (task.subtasks) {
stack.push(task.subtasks);
}
}
return result;
}
myCopy = flattenTasks(myTasks);