Doing an operator (==) equality check in js
I have the following class:
class Coord {
constructor(x, y) {
this.x = x;
this.y = y
}
equals(b) { // how to add this method?
return true;
}
}
let p1 = new Coord(1,2);
let p2 = new Coord(1,2);
console.assert(p1 == p2, 'points are not equal');
Is there a method I can add into the class such that p1 == p2
in the above? I'd like to do it within the class and not something like a JSONStringify
approach.
The equivalent in python I would do would be:
class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, o):
return (self.x == o.x) and (self.y == o.y)
p1 = Coord(1,2);
p2 = Coord(1,2);
print (p1==p2)
# True
There you go :)
class Coord {
constructor(x, y) {
this.x = x;
this.y = y
}
print() {
console.log('(' + `%c${this.x}` + ', ' + `%c${this.y}` + '%c)', "color:red", "color: blue", "color: black");
}
equals(b) {
return (this.x===b.x && this.y===b.y);
}
}
let p1 = new Coord(1,2);
let p2 = new Coord(1,2);
let p3 = new Coord(1,3);
let p4 = new Coord(4,2);
console.assert(p1.equals(p2), 'p1 and p2 are not equal');
console.assert(p1.equals(p3), 'p1 and p3 are not are not equal');
console.assert(p1.equals(p4), 'p1 and p4 points are not equal');
An alternative
class Coord {
constructor(x, y) {
this.x = x;
this.y = y
}
valueOf(b) {
return `${x},${y}`
}
}
let p1 = new Coord(1,2);
let p2 = new Coord(1,2);
console.assert(p1.valueOf() == p2.valueOf(), 'points are not equal');
If you are trying to compare two instances of the Coord
class you will not be able to do that within the class itself. How you have it set up seems like a decent approach. You could also compare the coordinate values before creating the class.