68 lines
1.9 KiB
JavaScript
68 lines
1.9 KiB
JavaScript
function Complex(real, imaginary) {
|
|
BaseObject.call(this);
|
|
this.real = real || 0;
|
|
this.imaginary = imaginary || 0;
|
|
}
|
|
|
|
Complex.prototype = Object.create(BaseObject.prototype);
|
|
Complex.prototype.constructor = Complex;
|
|
|
|
Complex.prototype.setReal = function (real) {
|
|
this.real = real;
|
|
this.registerAction('setReal', [real]);
|
|
};
|
|
|
|
Complex.prototype.setImaginary = function (imaginary) {
|
|
this.imaginary = imaginary;
|
|
this.registerAction('setImaginary', [imaginary]);
|
|
};
|
|
|
|
Complex.prototype.getReal = function () {
|
|
this.registerAction('getReal', []);
|
|
return this.real;
|
|
};
|
|
|
|
Complex.prototype.getImaginary = function () {
|
|
this.registerAction('getImaginary', []);
|
|
return this.imaginary;
|
|
};
|
|
|
|
Complex.prototype.add = function (other) {
|
|
this.real += other.real;
|
|
this.imaginary += other.imaginary;
|
|
this.registerAction('add', [other]);
|
|
};
|
|
|
|
Complex.prototype.subtract = function (other) {
|
|
this.real -= other.real;
|
|
this.imaginary -= other.imaginary;
|
|
this.registerAction('subtract', [other]);
|
|
};
|
|
|
|
Complex.prototype.multiply = function (other) {
|
|
const real = this.real * other.real - this.imaginary * other.imaginary;
|
|
const imaginary = this.real * other.imaginary + this.imaginary * other.real;
|
|
this.real = real;
|
|
this.imaginary = imaginary;
|
|
this.registerAction('multiply', [other]);
|
|
};
|
|
|
|
Complex.prototype.divide = function (other) {
|
|
const denominator =
|
|
other.real * other.real + other.imaginary * other.imaginary;
|
|
const real =
|
|
(this.real * other.real + this.imaginary * other.imaginary) /
|
|
denominator;
|
|
const imaginary =
|
|
(this.imaginary * other.real - this.real * other.imaginary) /
|
|
denominator;
|
|
this.real = real;
|
|
this.imaginary = imaginary;
|
|
this.registerAction('divide', [other]);
|
|
};
|
|
|
|
Complex.prototype.toString = function () {
|
|
this.registerAction('toString', []);
|
|
return `${this.real} + ${this.imaginary}i`;
|
|
};
|