forked from anvaka/ngraph.fromjson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
47 lines (37 loc) · 1.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
module.exports = load;
var createGraph = require("@patagona-technologies/ngraph.graph");
function load(jsonGraph, nodeTransform, linkTransform) {
var stored;
nodeTransform = nodeTransform || id;
linkTransform = linkTransform || id;
if (typeof jsonGraph === "string") {
stored = JSON.parse(jsonGraph);
} else {
stored = jsonGraph;
}
var graph = createGraph({ multigraph: true }),
i;
if (stored.links === undefined || stored.nodes === undefined) {
throw new Error("Cannot load graph without links and nodes");
}
for (i = 0; i < stored.nodes.length; ++i) {
var parsedNode = nodeTransform(stored.nodes[i]);
if (!parsedNode.hasOwnProperty("id")) {
throw new Error("Graph node format is invalid: Node id is missing");
}
graph.addNode(parsedNode.id, parsedNode.data);
}
for (i = 0; i < stored.links.length; ++i) {
var link = linkTransform(stored.links[i]);
if (!link.hasOwnProperty("fromId") || !link.hasOwnProperty("toId")) {
throw new Error(
"Graph link format is invalid. Both fromId and toId are required"
);
}
graph.addLink(link.fromId, link.toId, link.data);
}
return graph;
}
function id(x) {
return x;
}