Complex

Complex numbers

by evgkch

JavaScript

class Complex {

	static add(z1, z2) {
  	return {
    	re: z1.re + z2.re,
      im: z1.im + z2.im,
    };
  }
  
  static multiply(z1, z2) {
  	return {
    	re: (z1.re * z2.re) - (z1.im * z2.im),
     	im: (z1.re * z2.im) + (z1.im * z2.re),
    };
  }
  
  static abs(z) {
  	return Math.sqrt((z.re * z.re) + (z.im * z.im));
  }
  
  static phi(z) {
  	return Math.atan(z.im / z.re);
  }
  
  static re(z) {
  	return z.abs * Math.cos(z.phi);
  }
  
  static im(z) {
  	return z.abs * Math.sin(z.phi);
  }

	get conj() {
  	return new Complex(this.re, -this.im);
  }
  
  get log() {
  	const isImNegative = this.im < 0;
  	const result = `${this.re} ${isImNegative ? '-' : '+'} ${isImNegative ? -this.im : this.im}i`;
    console.log(result);
  	return this;
  }

	constructor(re, im) {
  	this.re = re;
    this.im = im;
  }
  
  add(z) {
  	if (z instanceof Complex)
    {
    	const { re, im } = Complex.add(this, z);
      return new Complex(re, im);
    }
    else
    	throw new Error('instance of added value must be a Complex');
  }
  
  multiply(z) {
  	if (z instanceof Complex)
    {
    	const { re, im } = Complex.multiply(this, z);
      return new Complex(re, im);
    }
    else
    	throw new Error('instance of multiplied value must be a Complex');
  }
};

const z1 = new Complex(3,3);
const z2 = new Complex(4,4);

// console.log(Complex.phi(z1.log.conj.log.multiply(z2).log))

const str = 'I2 + 5i + s +   23';
const matchSpaces = /\s/g;
const re = /\d+|[i,I]*\d+[i,I]*/g;
console.log(str.replace(matchSpaces, '').match(re));