clone Graph - Node.js Data Structure

Node.js examples for Data Structure:Graph

Description

clone Graph

Demo Code


var Node = function (val) {
  this.data = val;//  ww  w.ja  va 2s. c om
  this.neighbors = {};
};

var Edge = function (weight, toNode) {
  this.weight = weight;
  this.toNode = toNode;
};

var Graph = function () {
  this.graphSet = {};
};

Graph.prototype.addNode = function (val) {
  var newNode = new Node(val);
  this.graphSet[val] = newNode;
  return newNode;
};

Graph.prototype.deleteNode = function (val) {
  var node = this.graphSet[val];
  for (var neighbor in node.neighbors) {
    if (node.neighbors[neighbor][val]) {
      delete node.neighbors[neighbor][val];
    }
  }
  delete node;
};

Graph.prototype.addEdge = function (fromNode, toNode, weight) {
  var weight = weight || 1;
  if (this.graphSet[fromNode] && this.graphSet[toNode]) {
    if (this.graphSet[toNode].neighbors[fromNode]) {
      this.graphSet[toNode].neighbors[fromNode].weight = weight;
    }
    var newEdge = new Edge(weight, this.graphSet[toNode]);
    this.graphSet[fromNode].neighbors[toNode] = newEdge;
  } else {
    console.error("Error, both node's do not exist");
  }
};

var newGraph = new Graph();
newGraph.addNode(5);
newGraph.addNode(10);
newGraph.addNode(4);
newGraph.addNode(3);
newGraph.addNode(1);
newGraph.addNode(6);
newGraph.addNode(7);
newGraph.addNode(13);
newGraph.addEdge(13, 1);
newGraph.addEdge(5, 7);
newGraph.addEdge(7, 5);
newGraph.addEdge(4, 5);
newGraph.addEdge(4, 6);
newGraph.addEdge(1, 5);
newGraph.addEdge(10, 4);
newGraph.addEdge(4, 10);
newGraph.addEdge(6, 1);
newGraph.addEdge(1, 3);
newGraph.addEdge(7, 3);
newGraph.addEdge(3, 4);
newGraph.addEdge(4, 7);

console.log(newGraph)

var cloneDirectedGraph = function (graph) {
  var hash = {};
  var clonedGraph = new Graph();
  
  function clone (node) {
    var stack = [];
    
    if (!hash[node.data]) {
      var newNode = clonedGraph.addNode(node.data);
      hash[node.data] = newNode;
      
      for (var neighbor in node.neighbors) {
        clone(node.neighbors[neighbor].toNode);
        stack.push({ toNode: neighbor, weight: node.neighbors[neighbor].weight });
      }
      
      for (var i = 0; i < stack.length; i++) {
        clonedGraph.addEdge(node.data, stack[i].toNode, stack[i].toNode.weight);
      }
    } 
  }
  
  clone(graph[Object.keys(graph)[0]]);
  
  return clonedGraph;
};

console.log(cloneDirectedGraph(newGraph.graphSet));

Related Tutorials