Last active
October 24, 2015 02:17
-
-
Save psema4/c83c867682a344b17f2d to your computer and use it in GitHub Desktop.
Basic JS Graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/* Creates a simple property graph using the adjacency-list strategy, based on | |
https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs | |
*/ | |
var nodes = [ | |
{ id: 0, label: 'Top' } | |
, { id: 1, label: 'Bottom Right' } | |
, { id: 2, label: 'Bottom Left' } | |
] | |
, graph = [ | |
[ [1, { label: 'STEP_1' }] ] | |
, [ [2, { label: 'STEP_2' }], [0, { label: 'START_OVER' }] ] | |
, [ [0, { label: 'FINISHED' }], [1, { label: 'UNDO' }] ] | |
] | |
; | |
function getNode(id) { | |
var node; | |
if (nodes[id]) { | |
node = nodes[id]; | |
} | |
return node; | |
} | |
function getRelations(id) { | |
var relations = []; | |
if (nodes[id]) { | |
var node = getNode(id); | |
for (var j=0; j<graph[id].length; j++) { | |
relations.push(graph[id][j]); | |
} | |
} | |
return relations; | |
} | |
function showRelationsForNode(id) { | |
var node = getNode(id) | |
, relations = getRelations(id) | |
; | |
for (var i=0; i<relations.length; i++) { | |
var relatedNode = getNode(relations[i][0]) | |
, relation = relations[i][1] | |
; | |
console.log('(n1:`%s`)-[r:`%s`]->(n2:`%s`)', node.label, relation.label, relatedNode.label); | |
} | |
} | |
showRelationsForNode(0); | |
showRelationsForNode(1); | |
showRelationsForNode(2); | |
/* OUTPUTS: | |
$ node test.js | |
(n1:`Top`)-[r:`STEP_1`]->(n2:`Bottom Right`) | |
(n1:`Bottom Right`)-[r:`STEP_2`]->(n2:`Bottom Left`) | |
(n1:`Bottom Right`)-[r:`START_OVER`]->(n2:`Top`) | |
(n1:`Bottom Left`)-[r:`FINISHED`]->(n2:`Top`) | |
(n1:`Bottom Left`)-[r:`UNDO`]->(n2:`Bottom Right`) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment