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
59 lines (51 loc) · 1.86 KB
/
fraction.ts
File metadata and controls
59 lines (51 loc) · 1.86 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
import { roundTo } from "./utils.ts";
export class Fraction {
constructor(
private numerator: number,
private denominator: number,
) {}
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;
}
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;
}
public multiply(other: Fraction) {
const newNumerator = this.numerator * other.numerator;
const newDenominator = this.denominator * other.denominator;
this.numerator = newNumerator;
this.denominator = newDenominator;
}
public divide(other: Fraction) {
const newNumerator = this.numerator * other.denominator;
const newDenominator = this.denominator * other.numerator;
this.numerator = newNumerator;
this.denominator = newDenominator;
}
public toFloat(precision: number): number {
return roundTo(this.numerator / this.denominator, precision);
}
public toString(): string {
return `${this.numerator}/${this.denominator}`;
}
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.parseFloat(parts[1].trim());
if (Number.isNaN(numerator) || Number.isNaN(denominator)) {
throw new Error(`non-numeric numerator/denominator`);
}
return new Fraction(numerator, denominator);
}
}