Class support for operators

One of the features that makes python such powerful language is that it allows for classes to act like built-in types through its magic methods. This allows for classes to be added together, to have specific behavior when iterated on, etc...

Example:

class Complex:
    def __init__(self, re, im):
        self.re = re
        self.im = im
    
    def __add__(self, other):
        a = self.re + other.re
        b = self.im + other.im
        return Complex(a,b)
               
    def __str__(self):
        return '{} + {}i'.format(self.re, self.im)
    
print(Complex(1,2) + Complex(3,4))
# returns 4 + 6i

Implementing something similar in JS could make it much more powerful when it comes to scientific calculations.

Example of how this could be implemented:

class Complex{
    constructor(re,im) {
        this.re = re
        this.im = im
    }
    operator add(arg) {
        // code
    }
}
2 Likes

See also:

2 Likes