Simple Implementation of a Graph

by vzufelt

HTML

<input type="button" onclick="createGraph();" value="Create Graph" />
<br/>
<br/> Select two nodes:
<br />From
<select id="from">
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
    <option value='D'>D</option>
    <option value='E'>E</option>
    <option value='F'>F</option>
    <option value='G'>G</option>
</select>
To
<select id="to">
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
    <option value='D'>D</option>
    <option value='E'>E</option>
    <option value='F'>F</option>
    <option value='G'>G</option>
</select>
<input type="button" onclick="calculate();" value="Calculate" />
<br/>
<p id="nodes"></p>
<br/>
<p id="edges"></p>
<br/>
<br/><span id="result" />

JavaScript

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

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

var Graph = function() {
  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);
    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;
  }

  this.calculatePaths = function() {
   	this.paths.push(v);
  if (v === w) {
  	this.print(path, cost);
  } else {
  	for (var i in this.edges[v]) {
    	if (!this.paths.includes(i)) {
      	var c1 = this.edges[v][i];
        var c2 = c1 + cost;
        this.calculate(i, w, c2, path);
      }
    }
  }
  this.paths.pop();
}
  }
  this.printPaths = function() {
    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 nodeList = document.getElementById("nodes");
var graph = new Graph(); 
function createGraph() {

  var a = graph.addNode('A');
  addNodeToCombo(a);
  var b = graph.addNode('B');
  addNodeToCombo(b);
  var c = graph.addNode('C');
  addNodeToCombo(c);
  var d = graph.addNode('D');
  addNodeToCombo(d);
  var e =...