Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Structure to represent a DAG in Javascript

I have a string that I need to parse into a graph (DAG) data structure using javascript. Included in the data structure are a few attributes I should store, such as the node's id, name, and a label that is given to the link if one exists to another node. So, an example would be

Node1 (id: 1, name: 'first') --('link name')--> Node2 (id:....)

and so forth. Once the data structure is created I do not need to do any more operations on it other than read it (I will later use it to render a visualization with d3). The amount of nodes will not be very many, as several of them are shared.

I am imagining an adjacency list but am not sure how I would encode that in javascript. For instance, I know a json object can have a "field" : "value" structure but can I do that with Object : [list of adjacent Objects]?

like image 518
Aaron Avatar asked Sep 28 '12 19:09

Aaron


People also ask

What is a DAG data structure?

A DAG is an information or data structure which can be utilized to demonstrate diverse problems. It is an acyclic graph in topological ordering. Each directed edge has a certain order followed by the node. Every DAG starts from a node that has no parents and end with one that has no kids. These graphs are never cyclic.

Is a binary tree a DAG?

Trees have direction (parent / child relationships) and don't contain cycles. They fit with in the category of Directed Acyclic Graphs (or a DAG). So Trees are DAGs with the restriction that a child can only have one parent.

Is JSON a DAG?

Any JSON object will most definitely be a DAG.


2 Answers

you can use lists (arrays) in json. E.g. I could represent a simple directed graph as

{
  "NodeA": {"name": "NodeA", "adjacentTo": ["NodeB", "NodeC"]},
  "NodeB": {"name": "NodeB", "adjacentTo": ["NodeC", "NodeD"]},
  "NodeC": {"name": "NodeC", "adjacentTo": ["NodeA"]},
  "NodeD": {"name": "NodeD", "adjacentTo": []}
}

This would be the graph:

C
^^
| \
|  \
A -> B -> D

The name field really isn't needed, but you can associate any attributes you want with a node that way.

like image 53
David Avatar answered Sep 30 '22 13:09

David


JavaScript objects must have string keys, but can store any type of value. Of course, the entire point in an id is to allow you to represent a complex type wirh a simple one.

var adjacentTo = {};
adjacentTo[node1.id] = [node2, node3]
like image 20
Eric Avatar answered Sep 30 '22 13:09

Eric