forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplexNumber.js
More file actions
73 lines (65 loc) · 1.77 KB
/
ComplexNumber.js
File metadata and controls
73 lines (65 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
export default class ComplexNumber {
/**
* @param {number} [real]
* @param {number} [imaginary]
*/
constructor({ real = 0, imaginary = 0 } = {}) {
this.real = real;
this.imaginary = imaginary;
}
/**
* @param {ComplexNumber} addend
* @return {ComplexNumber}
*/
add(addend) {
return new ComplexNumber({
real: this.real + addend.real,
imaginary: this.imaginary + addend.imaginary,
});
}
/**
* @param {ComplexNumber} subtrahend
* @return {ComplexNumber}
*/
subtract(subtrahend) {
return new ComplexNumber({
real: this.real - subtrahend.real,
imaginary: this.imaginary - subtrahend.imaginary,
});
}
/**
* @param {ComplexNumber} multiplicand
* @return {ComplexNumber}
*/
multiply(multiplicand) {
return new ComplexNumber({
real: this.real * multiplicand.real - this.imaginary * multiplicand.imaginary,
imaginary: this.real * multiplicand.imaginary + this.imaginary * multiplicand.real,
});
}
/**
* @param {ComplexNumber} divider
* @return {ComplexNumber}
*/
divide(divider) {
// Get divider conjugate.
const dividerConjugate = this.conjugate(divider);
// Multiply dividend by divider's conjugate.
const finalDivident = this.multiply(dividerConjugate);
// Calculating final divider using formula (a + bi)(a − bi) = a^2 + b^2
const finalDivider = (divider.real ** 2) + (divider.imaginary ** 2);
return new ComplexNumber({
real: finalDivident.real / finalDivider,
imaginary: finalDivident.imaginary / finalDivider,
});
}
/**
* @param {ComplexNumber} complexNumber
*/
conjugate(complexNumber) {
return new ComplexNumber({
real: complexNumber.real,
imaginary: -1 * complexNumber.imaginary,
});
}
}