Last active
May 19, 2017 22:20
-
-
Save Rantelo/e693a56096cf65bec283939a48eb6b7c to your computer and use it in GitHub Desktop.
Graph implementation
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
| class Node { | |
| constructor(name) { | |
| this.name = name; | |
| this.edges = []; | |
| } | |
| addEdge(edge) { | |
| this.edges.push(edge); | |
| } | |
| } | |
| class Graph { | |
| constructor(directed) { | |
| this.nodes = []; | |
| this.directed = directed ? true : false; | |
| } | |
| indexOf(name) { | |
| for (let i = 0; i < this.nodes.length; i++) { | |
| if (this.nodes[i].name === name) return i; | |
| } | |
| return -1; | |
| } | |
| addEdge(start, end) { | |
| const _this = this; | |
| const handleNodeEdge = function(vertex, other) { | |
| const index = _this.indexOf(vertex); | |
| if (index !== -1) { | |
| _this.nodes[index].addEdge(other); | |
| } else { | |
| const node = new Node(vertex); | |
| node.addEdge(other); | |
| _this.nodes.push(node); | |
| } | |
| } | |
| handleNodeEdge(start, end); | |
| if (!this.directed) handleNodeEdge(end, start); | |
| } | |
| toString() { | |
| let ans = `${this.directed ? 'directed' : 'non-directed'}\n`; | |
| for (let i = 0; i < this.nodes.length; i++) { | |
| ans += `${this.nodes[i].name} : [${this.nodes[i].edges}]\n`; | |
| } | |
| return ans | |
| } | |
| } | |
| module.exports = Graph; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment