0

I'm new to javascript, thus the question. I've the following object,

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

How do I check the presence of this object in a hash map. An analogy would be in Python I'd add the following method in the class,

def __eq__(self, other):
   return this.data == other.data

How can do a similar object comparison in javascript?

Melissa Stewart
  • 2,671
  • 8
  • 29
  • 72
  • There's no hash map in JavaScript. You have to explain which hash map implementation you're using – Juan Mendes Jan 28 '19 at 18:18
  • 3
    Native `==` object comparison in JavaScript is always based on the actual identity of the objects. Two different objects are never `==` no matter how similar they are. – Pointy Jan 28 '19 at 18:18
  • 1
    Marked it as duplicate since the other question is about custom object equality implementation that would integrate with `Map` or `Set`, which I think is what the OP wanted to achieve. – plalx Jan 28 '19 at 18:29

1 Answers1

0

What do you mean by hashmap in javascript? There is no such collection here.

Anyways, Equality depends on what the data is.

If its a value type (boolean, string, number), then you simply compare then via === or == operator. Where the later operator automatically convert either or both the sides (LHS/RHS) of the equation to make them the same type, so the following would suffice:

this.data === other.data; // value comparison; e.g: 1 === 3; is false

If its a reference type(array, object) then comparing both objects would result in a memory address check, where if they are different then it would result in false. If you would want to compare their values then you would have to iterate the index (for array) or keys (for object) in order to check for equality.

this.data === other.data; // reference comparison; this.data = [1,2,3] (memory = 1234), other.data = [1,2,3] (memory = 1235); is false
Danyal Imran
  • 1,862
  • 7
  • 17
  • The OP most likely referred to equality overloading for the `Map` and `Set` data structures in JavaScript. – plalx Jan 28 '19 at 18:31
  • @plalx he wants to overload via the ```data``` value, we don't know what data type is ```data```, so therefore telling him how equality works behind the scene, he may get a hint on how to set the equality of his data structure. – Danyal Imran Jan 28 '19 at 18:33