JSFiddle - React, Tailwind, and code Playground

by leiperte

HTML

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

JavaScript

//Assignment 14


var Node = function(_name) {
  this.name = _name;
  this.discovered = false;
  this.edges = [];
  return this;
}

var Edge = function(_from, _to, _cost) {
  this.from = _from;
  this.to = _to;
  this.cost = _cost;
  return this;
}

var Traversal = function() {
  this.path = [];
  this.cost = 0;
}

var Graph = function() {

  // This is a specific implementation of a graph
  // that uses nodes edges and paths. There are many
  // more ways to implement a graph and you should 
  // research them

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

  this.addNode = function(_name) {
    var node = new Node(_name);
    this.nodes.push(node);
    return node;
  };

  this.addEdge = function(_from, _to, _cost) {
    var edge = new Edge(_cost);
    edge.from = _from;
    edge.to = _to;
    edge.cost = _cost;
    this.edges.push(edge);
    _from.edges.push(edge);
    _to.edges.push(edge);
    return edge;
  };

  this.printNodes = function() {
    var s = "All Nodes in Graph <br/>";
    for (var i = 0; i < this.nodes.length; i++) {
      s = s + "Node: " + i + "   Name: " + this.nodes[i].name + "</br>";
    }
    return s;
  }

  this.printEdges = function() {
    var s = "All Edges in Graph <br/>";
    for (var i = 0; i < this.edges.length; i++) {
      s += "Edge: " + i + "   From: " + this.edges[i].from.name + "   To: " + this.edges[i].to.name + "   Cost: " + this.edges[i].cost + "</br>";
    }
    return s;
  }


  // Must implement
  this.calculatePaths = function(_start, _end) {
    var start = _start;
    var end = _end;
    traveler.path.push(start.name);
    start.discovered = true;
    if (start.name == end.name) {
      start.discovered = false;
      this.paths.push(traveler);
      traveler = new Traversal();
      return this;
    }
    for (var i = 1; i < start.edges.length; i++) {
      if (start.edges[i].to.discovered == false) {
        traveler.cost += start.edges[i].cost;
        this.calculatePaths(start.edges[i].to, end);
   ...