/**
*
*/
class Complex {
constructor(real, imaginary) {
this._real = real; // Private variable for real part
this._imaginary = imaginary; // Private variable for imaginary part
}
from(array) {
// TODO validation
return new Complex(array[0], array[1]); // Private variable for imaginary part
}
// ✅ Getter for the real part
get real() {
return this._real;
}
// ✅ Setter for the real part
set real(value) {
if (typeof value !== "number") throw new Error("Real part must be a number");
this._real = value;
}
// ✅ Getter for the imaginary part
get imaginary() {
return this._imaginary;
}
// ✅ Setter for the imaginary part
set imaginary(value) {
if (typeof value !== "number") throw new Error("Imaginary part must be a number");
this._imaginary = value;
}
// ✅ Compare two complex numbers (checks if both real and imaginary parts match)
equals(other) {
if (!(other instanceof Complex)) throw new Error("Can only compare with another Complex number");
return this.real === other.real && this.imaginary === other.imaginary;
}
// ✅ Convert to string representation (e.g., "3 + 4i" or "-2 - 5i")
toString() {
const sign = this.imaginary >= 0 ? "+" : "-";
return `${this.real} ${sign} ${Math.abs(this.imaginary)}i`;
}
// ✅ Add another complex number
add(other) {
if (!(other instanceof Complex)) throw new Error("Can only add another Complex number");
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
// ✅ Subtract another complex number
subtract(other) {
if (!(other instanceof Complex)) throw new Error("Can only subtract another Complex number");
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
// ✅ Multiply by another complex number
multiply(other) {
if (!(other instanceof Complex)) throw new Error("Can only multiply by another Complex number");
return new Complex(
this.real * other.real - this.imaginary * other.imaginary,
this.real * other.imaginary + this.imaginary * other.real
);
}
// ✅ Divide by another complex number
divide(other) {
if (!(other instanceof Complex)) throw new Error("Can only divide by another Complex number");
const denominator = other.real ** 2 + other.imaginary ** 2;
if (denominator === 0) throw new Error("Cannot divide by zero");
return new Complex(
(this.real * other.real + this.imaginary * other.imaginary) / denominator,
(this.imaginary * other.real - this.real * other.imaginary) / denominator
);
}
}