// 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());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.