Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable a Rational class to handle math operators

I have this Rational class that has a method for each operation (add,mult etc)

function Rational(nominator, denominator){
    this.nominator = nominator;
    this.denominator = denominator || 1;    
}

Rational.prototype = {
    mult: function(that) {
        return new Rational(
            this.nominator * that.nominator,
            this.denominator * that.denominator
            );
    },
    print: function() {
        return this.nominator + '/' + this.denominator;
    }
};

var a = new Rational(1,2),
    b = new Rational(3);

console.log( a.mult(b).print() ); // 3/2

Can I make it more "natural" e.g. to enable console.log( a * b ) ?

like image 833
Xlaudius Avatar asked Jun 14 '13 11:06

Xlaudius


1 Answers

You can't overload operators (read similar questions).

Moreover, a dedicated method like mult can be treated as a sign of good design (not only in Javascript), since changing the original operator behavior can confuse users (well, a rational number actually a good candidate for overloading).

You can change print to toString as user thg435 has suggested.

Going even further:

Rational.prototype = {
    mult : ... ,
    toString: ... ,
    valueOf: function() { return this.nominator / this.denominator; }
};

this will enable the a * b syntax (note: you don't operate on Rationals any more, but rather on primitives).

like image 159
emesx Avatar answered Sep 18 '22 07:09

emesx