小能豆

javascript consoling didn't return expected result

javascript

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


阅读 77

收藏
2023-12-21

共1个答案

小能豆

The behavior you’re observing is related to the case sensitivity of JavaScript object keys. In JavaScript, object keys are case-sensitive. In your removeEdge method, when you filter the array, you are using el !== v2, where v2 is “Tokyo” (with an uppercase “T”). However, in your graph, the vertex is stored as “tokyo” (with a lowercase “t”). JavaScript treats these as different keys.

To fix this issue, you can ensure that the vertices are consistently stored in a specific case, for example, in lowercase. You can modify your addVertex and other methods to ensure this consistency:

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

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

  addEdge(v1, v2) {
    const lowerV1 = v1.toLowerCase();
    const lowerV2 = v2.toLowerCase();
    this.adjacencyList[lowerV1].push(lowerV2);
    this.adjacencyList[lowerV2].push(lowerV1);
  }

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

With these changes, your graph’s vertices will be consistently stored in lowercase, and you should get the expected behavior in your console.log statements.

2023-12-21