Search code examples
javascriptclassdata-structuresgraphconsole.log

javascript consoling didn't return expected result


I am trying to learn graph datastructure and found this weird behaviour by consoling the current data, my main code is as follows

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
  }

  addEdge(v1, v2) {
    this.adjacencyList[v1].push(v2);
    this.adjacencyList[v2].push(v1);
  }

  removeEdge(v1, v2) {
    this.adjacencyList[v1] = this.adjacencyList[v1].filter((el) => el !== v2);
    this.adjacencyList[v2] = this.adjacencyList[v2].filter((el) => el !== v1);
  }
}

and my console logs were

let graph = new Graph();
graph.addVertex("tokyo");
graph.addVertex("dallas");
graph.addVertex("aspen");

graph.addEdge("tokyo", "dallas");
graph.addEdge("dallas", "aspen");

console.log(graph.adjacencyList);

graph.removeEdge("dallas", "tokyo");

console.log(graph.adjacencyList);

what I normally expected was the first console.log before removing should contain the edges and the after would contain the edges after removed, that is what I also see in the object

{tokyo: Array(1), dallas: Array(2), aspen: Array(1)}

{Tokyo: Array(0), dallas: Array(1), aspen: Array(1)}

but when I open up the object I don't see the expected values in object 1

aspen: ['dallas']
dallas: ['aspen']
Tokyo: []

This is exactly the same for the second object in console.log


Solution

  • Before logging the object, create a clone of it:

    structuredClone(graph.adjacencyList)

    This way the reference is a new object at the time the adjacently "list" was logged.

    class Graph {
      constructor() {
        this.adjacencyList = {};
      }
      addVertex(vertex) {
        if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
      }
      addEdge(v1, v2) {
        this.adjacencyList[v1].push(v2);
        this.adjacencyList[v2].push(v1);
      }
      removeEdge(v1, v2) {
        this.adjacencyList[v1] = this.adjacencyList[v1].filter((el) => el !== v2);
        this.adjacencyList[v2] = this.adjacencyList[v2].filter((el) => el !== v1);
      }
    }
    
    let graph = new Graph();
    graph.addVertex("tokyo");
    graph.addVertex("dallas");
    graph.addVertex("aspen");
    
    graph.addEdge("tokyo", "dallas");
    graph.addEdge("dallas", "aspen");
    
    console.log(structuredClone(graph.adjacencyList));
    
    graph.removeEdge("dallas", "tokyo");
    
    console.log(structuredClone(graph.adjacencyList));
    .as-console-wrapper { top: 0; max-height: 100% !important; }