Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
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
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!