JSFiddle - React, Tailwind, and code Playground

by Tori Hoelscher

HTML

<input type="button" onclick="createGraph();" value="Create Graph" />
<br/> Select from two nodes:
<br />From
<select id="from"></select>
To
<select id="to"></select>
<input type="button" onclick="calculate();" value="Calculate" />
<p id="paths"></p>
<p id="nodes"></p>
<p id="edges"></p>

JavaScript

var Graph = function() {

  this.edges = [];
  this.paths = [];

  this.addNode = function(name) {
    this.edges[name] = [];
  }

  this.addEdge = function(from, to, cost) {
    this.edges[from][to] = cost;
    this.edges[to][from] = cost;
  }

  this.makeNodes = function() {
    var n = "Nodes in Graph: <br/>";
    var i = 1;
    for (var node in this.edges) {
      n = n + "Node: " + i + " Name: " + node + "</br>";
      i++;
    }
    return n;
  }

  this.calculatePaths = function(from, to, cost, paths) {
    this.paths.push(from);
    if (from == to) {
      this.printPaths(paths, cost);
    } else {
      for (var next in this.edges[from]) {
        if (this.paths.includes(next) == false) {
          var runCost = this.edges[from][next];
          var total = cost + runCost;
          this.calculatePaths(next, to, total, paths);
        }
      }
    }
    this.paths.pop();
  }

  this.printPaths = function(paths, cost) {
    var str = this.paths[0];
    for (var i = 1; i < this.paths.length; i++) {
      str = str + ", " + this.paths[i];
    }
    str += ": " + cost + "<br />";
    document.getElementById("paths").innerHTML += str;
  }
}

var g = new Graph();

function createGraph() {
  g.addNode("A");
  addNodeToCombo("A");
  g.addNode("B");
  addNodeToCombo("B");
  g.addNode("C");
  addNodeToCombo("C");
  g.addNode("D");
  addNodeToCombo("D");
  g.addNode("E");
  addNodeToCombo("E");
  g.addNode("F");
  addNodeToCombo("F");
  g.addNode("G");
  addNodeToCombo("G");

  g.addEdge("A", "B", 2);
  g.addEdge("A", "C", 1);
  g.addEdge("B", "D", 1);
  g.addEdge("B", "G", 1);
  g.addEdge("C", "D", 1);
  g.addEdge("C", "E", 1);
  g.addEdge("D", "E", 2);
  g.addEdge("D", "F", 1);
  g.addEdge("D", "G", 2);

 function makeEdges() {
    var e = "All Edges in Graph: <br/>";
    e += "Edge: 1 From: A To: B Cost: 2 </br>";
    e += "Edge: 2 From: A To: C Cost: 1 </br>";
    e += "Edge: 3 From: B To: D Cost: 1 </br>";
    e += "Edge: 4 From: B To: G Cost: 1 </br>";
    e...