forked from m426-2026/math
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfraction.ts
More file actions
91 lines (74 loc) · 2.45 KB
/
fraction.ts
File metadata and controls
91 lines (74 loc) · 2.45 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
import { roundTo } from "./utils.ts";
import { gcdBruteForce } from "./gcd.ts";
export class Fraction {
constructor(
private numerator: number,
private denominator: number,
) {
if (denominator === 0) {
throw new Error("denominator cannot be 0");
}
this.cancel();
}
public add(other: Fraction) {
const newNumerator =
this.numerator * other.denominator + other.numerator * this.denominator;
const newDenominator = this.denominator * other.denominator;
this.numerator = newNumerator;
this.denominator = newDenominator;
this.cancel();
}
public subtract(other: Fraction) {
const newNumerator =
this.numerator * other.denominator - other.numerator * this.denominator;
const newDenominator = this.denominator * other.denominator;
this.numerator = newNumerator;
this.denominator = newDenominator;
this.cancel();
}
public multiply(other: Fraction) {
const newNumerator = this.numerator * other.numerator;
const newDenominator = this.denominator * other.denominator;
this.numerator = newNumerator;
this.denominator = newDenominator;
this.cancel();
}
public divide(other: Fraction) {
const newNumerator = this.numerator * other.denominator;
const newDenominator = this.denominator * other.numerator;
this.numerator = newNumerator;
this.denominator = newDenominator;
this.cancel();
}
public toFloat(precision: number): number {
return roundTo(this.numerator / this.denominator, precision);
}
public toString(): string {
return `${this.numerator}/${this.denominator}`;
}
public cancel(): Fraction {
const gcd = gcdBruteForce(this.numerator, this.denominator);
this.numerator /= gcd;
this.denominator /= gcd;
if (this.denominator < 0) {
this.numerator *= -1;
this.denominator *= -1;
}
return this;
}
public static parse(expression: string): Fraction {
const parts = expression.split("/");
if (parts.length != 2) {
throw new Error(`illegal syntax: "[numerator]/[denominator]" required`);
}
const numerator = Number.parseInt(parts[0].trim());
const denominator = Number.parseInt(parts[1].trim());
if (Number.isNaN(numerator) || Number.isNaN(denominator)) {
throw new Error(`non-numeric numerator/denominator`);
}
if (denominator === 0) {
throw new Error("denominator cannot be 0");
}
return new Fraction(numerator, denominator);
}
}