-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFraction.ts
More file actions
111 lines (85 loc) · 2.57 KB
/
Fraction.ts
File metadata and controls
111 lines (85 loc) · 2.57 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
export class Fraction {
private integer: number = 1;
private fraction: number = 1;
constructor(a: number|Fraction, b: number = 1) {
if (a instanceof Fraction) {
this.integer = a.integer;
this.fraction = a.fraction;
} else if ( b === undefined) {
this.integer = Math.floor(a);
let residue = a - this.integer;
this.fraction = Math.floor(residue.toString().length * residue)
} else if (b !== undefined) {
this.integer = a;
this.fraction = b;
}
}
plus(value: Fraction|number): Fraction {
let that: Fraction = new Fraction(1,1);
if (value instanceof Number) {
that = new Fraction(value,1);
} else {
that = <Fraction>value;
}
let num = this.integer * that.fraction + that.integer * this.fraction;
let den = this.fraction * that.fraction;
if(den < 0){
num = -num;
den = -den;
}
return new Fraction(num, den);
}
toNumber() : number{
return this.integer / this.fraction
}
neg(){
return new Fraction(-this.integer, this.fraction)
}
multiply(value: Fraction|number): Fraction {
let num = 1;
let den = 0;
if(typeof(value) === "number"){
num = this.integer * value;
den = this.fraction;
}
else{
num = this.integer * value.integer;
den = this.fraction * value.fraction
}
if(den < 0){
num = -num;
den = -den;
}
return new Fraction(num, den) ;
}
divide(value: Fraction|number): Fraction {
return typeof(value) === "number" ? new Fraction(this.integer, this.fraction*value) : new Fraction(this.integer * value.fraction, this.fraction*value.integer);
}
inv(){
if(this.integer === 0)
throw new Error ("CANT INVERT FRACTION 0")
return this.integer<0 ? new Fraction(-this.fraction, -this.integer) : new Fraction(this.fraction, this.integer)
}
minus(value: Fraction|number): Fraction {
return this.plus(new Fraction(value).multiply(-1));
}
isZero(){
return this.integer===0
}
isOne(){
return this.integer===this.fraction
}
equals(f: Fraction){
return this.integer*f.fraction === this.fraction*f.integer
}
toString() {
return this.fraction===1 ? `${this.integer}` : `${this.integer}/${this.fraction}`;
}
static zero(){
return new Fraction(0,1)
}
static one(){
return new Fraction(1,1)
}
}
export default Fraction;