Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading