Some minor recommendations:
- Make it immutable.
It's generally a good thing to design for immutability when it's not overly complicated to do so. Take this code snippet for example:
const x = 2
fn(x)
console.log(x) // 2
It's going to output 2. You know it will because numbers are immutable, so there's nothing that fn()
can do to change the value of that number. However, the same can't be said for this piece of logic, because your class is mutable:
const x = new Complex(2, 0);
fn(x);
console.log(x); // ??
fn()
could be altering the value of x, and there's no way for you to know if it will or not without looking at the definition of fn()
.
Here's how I might go about making it immutable and still easy to work with:
class Complex {
constructor(real,imag) {
this.real = real;
this.imag = imag;
Object.freeze(this); // See here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
}
withRealPart(newReal) {
return new Complex(newReal, this.imag);
}
withImaginaryPart(newImaginary) {
return new Complex(this.real, newImaginary);
}
// Remove the setReal() and setImag() functions
...
}
Though, the withRealPart()
and withImaginaryPart()
functions might not even be that necessary. If you don't find yourself using them a lot, just get rid of them. It's probably more common to create an entirely new imaginary number or to add/subtract them, than to replace a single "part" with a new value.
- Toss the useless getters
They weren't doing anything anyways. You had publicly exposed the "real" and "imag" properties, letting anyone directly see or alter those public properties without going through your getters or setters, so why would they bother using those functions? Even if you had made those properties private, I would have suggested that you just make them public and toss the getters/setters, they're just noise in this scenario. (you may find some purist OOP people who will disagree with me on this, so feel free to look around and make your own opinions on this matter).
- Improve naming
This point doesn't matter that much, but I would recommend just spelling out the full "imaginary" word in your code. It doesn't take up that much more room, and is a little easier to read (and, you should in general optimize for reading, not writing). Perhaps, consider calling your class ComplexNumber
as well, to make it more apparent what it's for. (I originally thought, from this question's title, that you were literally trying to make an arbitrarily complex class full of complex logic. It wasn't until I looked at your code snippet that I realized you were just trying to work with complex numbers).