complex.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/start_class/complex.js
 

export class ComplexT {
     #real = 0
     #imag

     constructor ( a = 0, b = 0) {
         this.#real = a
         this.#imag = b
     }

     toString() {
         return this.#real + '+' + this.#imag + 'i'
     }

     Real() {
         return this.#real
     }

     Imag() {
         return this.#imag
     }

     Add( other ) {
        let rv = new ComplexT(this.#real, this.#imag)

        rv.#real += other.#real
        rv.#imag += other.#imag

        return rv
     }

         Sub(other) {
       let rv = new ComplexT(this.#real,this.#imag);
       rv.#real -= other.#real;
       rv.#imag -= other.#imag;
       return (rv);
    }

    Mult(other) {
       let rv = new ComplexT(0, 0);
       rv.#real = this.#real * other.#real - this.#imag * other.#imag;
       rv.#imag = this.#real * other.#imag + this.#imag * other.#real;
       return(rv);
    }

    Div(other) {
       let rv = new ComplexT(0, 0);
       let tmp = other.#real * other.#real + other.#imag * other.#imag;
       rv.#real = (this.#real * other.#real + this.#imag * other.#imag)/tmp;
       rv.#imag = (this.#imag * other.#real - this.#real * other.#imag)/tmp;
       return(rv);
    }

    Mag() {
       return Math.sqrt(this.#real * this.#real + this.#imag * this.#imag);
    }
}