All too often, programmers try to force the data to fit into a strict hierarchy,
with nested data structures. (
DOM manipulation and Javascript Data Structures: Flat or Structured? ,
Hierarchy Considered Harmful, etc. )
However, non-nested structures are better when you don't have a pure hierarchy.
Sometimes they work better even when you do have a pure hierarchy --
such as when you want to look up things without traversing the entire structure.
For example,
"What tasks depend on the sub-task named 'rotate stock' ?"
Perhaps one of the many alternatives to hierarchy
might work better in your case.
For example, an associative array:
<script>
"use strict";
// global task list
var tasklist_by_id = [];
var task_name_to_id = {};
// add a new task to global tasklist
function add_task(id, name, supertaskid){
tasklist_by_id[ id ] = {"id":id, "name":name, "supertaskid":supertaskid};
/* in other words,
var new_task = {};
new_task.id = id;
new_task.name = name;
new_task.supertaskid = supertaskid;
tasklist_by_id[ id ] = new_task;
*/
task_name_to_id[ name ] = id;
};
function ancestors_of( task_id ){
if( task_id ){
var my_name = tasklist_by_id[ task_id ].name;
var my_supertaskid = tasklist_by_id[task_id].supertaskid;
var my_ancestors = ancestors_of( my_supertaskid );
var ancestor_string = " -- " + my_name + my_ancestors;
return ancestor_string;
}else{
return ".";
};
};
function test(){
add_task( 1, "Main task #1", 0 );
add_task( 2, "Subtask 1", task_name_to_id[ "Main task #1" ] );
add_task( 3, "Sub-subtask 1", task_name_to_id[ "Subtask 1" ] );
add_task( 4, "Another Subtask of Main task 1", task_name_to_id[ "Main task #1" ] );
add_task( 5, "Sub-sub-subtask 1", task_name_to_id[ "Sub-subtask 1" ] );
add_task( 6, "rotate_stock", task_name_to_id["Sub-sub-subtask 1" ])
// What task is the parent task(s) of "rotate_stock" ?
var some_task_name = "rotate_stock";
var some_task_id = task_name_to_id[some_task_name];
var ancestors = ancestors_of( some_task_id );
alert("The ancestry line of " + some_task_name + " is " + ancestors);
}
test();
</script>