-1

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 
1

4 Answers 4

2

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');

Sign up to request clarification or add additional context in comments.

Comments

1

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'); 

3 Comments

@mathieu -- I see, I think that's the closest approach. But so in modern js there is no way to override the bare == check?
Nope, not at the moment.
@MatthieuRiegler -- It's kinda an anti-pattern to override natively available methods like valueOf. It can lead to bugs in code. The better approach would be to have a non-native method for the same.
1

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.

2 Comments

I see, so there's no way to override the == operator, like you could do in python with __eq__ ?
No way no, but you could do p1.valueOf() == p2.valueOf()
0

One option is using lodash (https://lodash.com/docs/4.17.15#isEqual)

Example from lodash documentation:

var object = { 'a': 1 }; var other = { 'a': 1 }; _.isEqual(object, other); // => true object === other; // => false

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.