function Complex(R , I){
if( isNaN( R ) || isNaN( I )) { throw new TypeError('Complex params require Number'); }
this.r = R;
this.i = I;
}
Complex.prototype.add = function (that) {
return new Complex(this.r + that.r, this.i + that.i);
};
Complex.prototype.neg = function () {
return new Complex(-this.r, -this.i);
};
Complex.prototype.multiply = function (that) {
if (this.r === that.r && this.i + that.i === 0) {
return this.r * this.r + this.i * this.i
}
return new Complex(this.r * that.r - this.i * that.i, this.r * that.i + this.i * that.r);
};
Complex.prototype.divide = function (that) {
var a = this.r;
var b = this.i;
var c = that.r;
var d = that.i;
return new Complex((a * c + b * d) / (c * c + d * d), (b * c - a * d) / (c * c + d * d));
};
Complex.prototype.mo = function () {
return Math.sqrt(this.r * this.r + this.i * this.i);
};
Complex.prototype.toString = function () {
return "{" + this.r + "," + this.i + "}";
};
Complex.prototype.equal = 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 {
var execres = Complex.parseRegExp.exec(s);
return new Complex(parseFloat(execres[1]), parseFloat(execres[2]));
} catch (e) {
throw new TypeError("Can't parse '" + s + "'to a complex");
}
};
Complex.parseRegExp = /^\{([\d\s]+[^,]*),([\d\s]+[^}]*)\}$/;
var c = new Complex(2, 3);
var d = new Complex(2, 5);
console.log(c.add(d).toString());
console.log(Complex.parse(c.toString()).add(c.neg()).equal(Complex.ZERO));
console.log(c.divide(d).toString(), Complex.parse('{2h, 09d}').mo())
console.log(new Complex(2, 3).multiply(new Complex(2, -3)))
{4,8}
true
{0.6551724137931034,-0.13793103448275862} Complex { r: 2, i: 9 }
13
(base) leooo-de-mbp:leo-py mac$ node js-complex.js
{4,8}
true
{0.6551724137931034,-0.13793103448275862} 9.219544457292887
13
複製代碼