Skip to content

Instantly share code, notes, and snippets.

@lupuszr
Created March 28, 2019 13:27
Show Gist options
  • Save lupuszr/fbc96a21bd6d8b709c7abdb2d2fb495c to your computer and use it in GitHub Desktop.
Save lupuszr/fbc96a21bd6d8b709c7abdb2d2fb495c to your computer and use it in GitHub Desktop.
Simple Complex number lib
function Complex(re, im) {
this.re = re;
this.im = im;
return this;
}
Complex.of = function (r, i) {
return new Complex(r,i);
}
Complex.re = function(complex) {
return complex.re;
}
Complex.im = function(complex) {
return complex.im;
}
Complex.magnitude = function(complex) {
return Math.sqrt(complex.re * complex.re + complex.im * complex.im);
}
Complex.argument = function(complex) {
if (complex.re > 0 || complex.im !== 0) {
return 2 * Math.atan(complex.im/(Math.sqrt(complex.re*complex.re + complex.im*complex.im) + complex.im))
}
if (compex.re < 0 && complex.im === 0) {
return Math.pi;
}
if (x === 0 && y === 0) {
return undefined;
}
}
Complex.prototype.add = function(oc) {
return Complex.of(this.re + oc.re, this.im + oc.im)
}
Complex.prototype.substract = function(oc) {
return Complex.of(this.re - oc.re, this.im - oc.im)
}
//xu - yv , xv + yu
Complex.prototype.multiply = function(oc) {
return Complex.of(this.re*oc.re - this.im*oc.im, this.im*oc.re + this.re*oc.im)
}
Complex.prototype.div = function(oc) {
const re = (this.re*om.re + this.im*om.im)/(this.re*this.re+this.im*this.im)
const im = (this.re*om.re - this.im*om.im)/(this.re*this.re+this.im*this.im)
return Complex.of(re, im)
}
Complex.prototype.map = function(fn) {
return Complex.of(fn(this.re), fn(this.im));
}
Complex.prototype.chain = function(fn) {
return fn(this.re, this.im)
}
const a = Complex.of(1,2).multiply(Complex.of(3,2)).add(Complex.of(4,4));
const b = a.chain((re, im) => Complex.of(re* 2, im)).map(a => a + 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment