JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<h3>Graph DS</h3>
JavaScript
class Graph {
constructor() {
this.graph = {}
}
addVertex(node) {
this.graph[node] = {
edges: {}
}
}
contains(node) {
return !!this.graph[node]
}
addEdge(startNode, endNode) {
// only if both nodes exist, add each node to the others edge list
if (this.contains(startNode) && this.contains(endNode)) {
this.graph[startNode].edges[endNode] = true
this.graph[endNode].edges[startNode] = true
}
}
hasEdge(node, edge) {
if (this.contains[node]) {
return !!this.graph[node].edges[edge]
}
}
removeEdge(startNode, endNode) {
if (this.contains(startNode) && this.contains(endNode)) {
delete this.graph[startNode].edges[endNode]
delete this.graph[endNode].edges[startNode]
}
}
removeVertex(node) {
if (this.contains(node)) {
// remove any existing edges this node has
for (let edge in this.graph[node].edges) {
this.removeEdge(node, edge)
}
delete this.graph[node]
}
}
}
let graph = new Graph()
graph.addVertex('the')
graph.addVertex('green')
graph.addVertex('apple')
graph.addEdge('the', 'green')
graph.addEdge('green', 'apple')
alert(JSON.stringify(graph))