I'm dealing with a pretty complex workflow that I want to represent as a JavaScript data structure. The flow is essentially a set of questions and answers where the answer to one question affects which question is asked next. The following is a basic example of what the flow might look like:
I'm not sure how to convert this flow into a JavaScript object that's easy to work with. I would ideally like to have a structure that's easy to loop/recurse through and that is easily modifiable, so that if someone wanted to change the flow at a later point, they could do so without having to make too many changes.
I feel like this is some sort of weird tree structure where nodes can have more than one parent. (I'm not sure what data structures like this are called.)
Anyway, the only idea I've had is to assign an ID to each node, and then create an array of node objects like the following:
{
id: 5,
parents: [2, 3],
children: [6, 7, 8]
}
However, that seems really inflexible when it comes to looping through the node objects (I could be wrong though).
If anyone could please offer some instruction/guidance on what kind of data structure(s) I should look into and possibly how to implement them in JavaScript, I would be greatly appreciative.
Thank you very much in advance.
Your initial idea will fit your scenario. Also, you already answered your own question regarding the data structure: JSON. I would stick with it.
There's only thing I would change: I don't think you need to save the parents, unless you have to go back from an answer to a question.
If this is the case you have a directed acyclic graph and this is the only structure I can think of in terms of your scenario.
There are a few frameworks out there who take care of implementing and visualizing this graphs in JS, refer to this question.
If you are going to implement this structure on your own, here's some (really basic) code to get you started:
var graph = graph || {};
graph.nodes = [
{id:1, children:[2,3]},
{id:2, children:[]},
{id:3, children:[4]},
{id:4, children:[]}
];
//Returns the next question-id for an answer-id
//or -1 if this was the last answer
graph.nextQForA = function(aId) {
for(var i = 0; i < graph.nodes.length; i++)
{
if(graph.nodes[i].id === aId && graph.nodes[i].children.length > 0 )
return graph.nodes[i].children[0];
}
return -1;
}
Usage as displayed here (Chrome console):
The traversal may as well be done recursively instead of iterative.