Skip to content

Instantly share code, notes, and snippets.

@Rantelo
Last active May 19, 2017 22:20
Show Gist options
  • Select an option

  • Save Rantelo/e693a56096cf65bec283939a48eb6b7c to your computer and use it in GitHub Desktop.

Select an option

Save Rantelo/e693a56096cf65bec283939a48eb6b7c to your computer and use it in GitHub Desktop.
Graph implementation
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