JavaScript The Definitive Guide - Ch. 9

9.3 A complex number class

by Denise Nepraunig

JavaScript

// All text and scripts are from JavaScript the definitve guide 6th edition

function Complex(real, imaginary) {
    if (isNaN(real) || isNaN(imaginary)) {
        throw new TypeError();
    }
    this.r = real;
    this.i = imaginary;
}

Complex.prototype.add = function (that) {
    return new Complex(this.r + that.r, this.i + that.i);
};

Complex.prototype.mul = function (that) {
    return new Comolex(this.r * that.r - this.i * that.i,
    this.r * that.i + this.i * that.r);
};

Complex.prototype.mag = function () {
    return Math.sqrt(this.r * this.r + this.i * this.i);
};

Complex.prototype.neg = function () {
    return new Complex(-this.r, -this.i);
};

Complex.prototype.toString = function () {
    return "{" + this.r + "," + this.i + "}";
};

Complex.prototype.equals = function (that) {
    return that !== null && that.constructor === Complex && this.r === that.r && this.i == that.i;
};

Complex.ZERO = new Complex(0, 0);
Complex.ONE = new Complex(1, 0);
Complex.I = new Complex(0, 1);

Complex.parse = function (s) {
    try { // Assume that the parsing will succeed
        var m = Complex._format.exec(s); // Regular expression magic
        return new Complex(parseFloat(m[1]), parseFloat(m[2]));
    } catch (x) { // And throw an exception if it fails
        throw new TypeError("Can't parse '" + s + "' as a complex number.");
    }
};

// A "private" class field used in Complex.parse() above.
Complex._format = /^\{([^,]+),([^}]+)\}$/;

var c = new Complex(2,3);
var d = new Complex(c.i, c.r);
var value = c.add(d).toString();
console.log(value);
var value2 = Complex.parse(c.toString()).add(c.neg()).equals(Complex.ZERO);
console.log(value2);

// because javascript is so dynamic, we can add properties even after objects were created
Complex.prototype.conj = function() {
    return new Complex(this.r, -this.i);
};
var e = c.conj();
console.log(c.toString());
console.log(e.toString());