Melissa Stewart
Melissa Stewart

Reputation: 3605

Graph implementation in Javascript

This is my graph implementation,

class Graph {
  constructor(directed = false) {
    this.numVertices = 0;
    this.directed = directed;
    this.dict = {}
  }

  addEdge(v1, v2, weight) {
    let p, q;
    if (v1 in this.dict) {
      p = this.dict[v1];
    } else {
      p = new Node(v1);
      this.dict[v1] = p;
      this.numVertices++;
    }
    if (v2 in this.dict) {
      q = this.dict[v2];
    } else {
      q = new Node(v2);
      this.dict[v2] = q;
      this.numVertices++;
    }
    p.addEdge(q);
  }
  stringify() {
    for (const [key, value] of Object.entries(this.dict)) {
      console.log(`${key}: ${value.adjacencySet}`);
    }
  }
}

// This is the node class.
class Node {
  constructor(data) {
    this.data = data;
    this.adjacencySet = new Set();
  }
  addEdge(node) {
    this.adjacencySet.add(node)
  }
  getAdjacentVertices() {
    return this.adjacencySet;
  }
}

// This is the calling client I'm using.
graph = new Graph();
graph.addEdge(12, 13);
graph.addEdge(12, 14);
graph.addEdge(13, 15);
graph.addEdge(14, 6);
graph.stringify();

When I run this, the representation of the graph I get is,

6: [object Set]
12: [object Set]
13: [object Set]
14: [object Set]
15: [object Set]

Ideally I want to print the values of the nodes in each element of the adjacency list. How do I print the data in the nodes.

Upvotes: 0

Views: 291

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You can convert the set to an array and then map the Nodes to their values.

[...value.adjacencySet].map(x => x.data)

class Graph {
  constructor(directed = false) {
    this.numVertices = 0;
    this.directed = directed;
    this.dict = {}
  }

  addEdge(v1, v2, weight) {
    let p, q;
    if (v1 in this.dict) {
      p = this.dict[v1];
    } else {
      p = new Node(v1);
      this.dict[v1] = p;
      this.numVertices++;
    }
    if (v2 in this.dict) {
      q = this.dict[v2];
    } else {
      q = new Node(v2);
      this.dict[v2] = q;
      this.numVertices++;
    }
    p.addEdge(q);
  }
  stringify() {
    for (const [key, value] of Object.entries(this.dict)) {
      console.log(`${key}: ${[...value.adjacencySet].map(x => x.data)}`);
    }
  }
}

// This is the node class.
class Node {
  constructor(data) {
    this.data = data;
    this.adjacencySet = new Set();
  }
  addEdge(node) {
    this.adjacencySet.add(node)
  }
  getAdjacentVertices() {
    return this.adjacencySet;
  }
}

// This is the calling client I'm using.
graph = new Graph();
graph.addEdge(12, 13);
graph.addEdge(12, 14);
graph.addEdge(13, 15);
graph.addEdge(14, 6);
graph.stringify();

Upvotes: 1

Related Questions