Created
July 1, 2024 11:07
-
-
Save reu/c199c1b3f68feb198a92443a20b2e718 to your computer and use it in GitHub Desktop.
Quick and dirty rational numbers in TS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Rational = { | |
numerator: number; | |
denominator: number; | |
simplify: () => Rational; | |
add: (other: Rational) => Rational; | |
sub: (other: Rational) => Rational; | |
mul: (other: Rational) => Rational; | |
div: (other: Rational) => Rational; | |
valueOf: () => number; | |
toString: () => string; | |
}; | |
export const rational = (n: number, d = 1): Rational => ({ | |
numerator: n, | |
denominator: d, | |
simplify: () => { | |
const gd = Math.abs(gcd(n, d)); | |
const g = d < 0 ? -gd : gd; | |
return rational(n / g, d / g); | |
}, | |
add: ({ numerator: n2, denominator: d2 }: Rational) => | |
rational(n * d2 + n2 * d, d * d2), | |
sub: ({ numerator: n2, denominator: d2 }: Rational) => | |
rational(n, d).add(rational(-n2, d2)), | |
mul: ({ numerator: n2, denominator: d2 }: Rational) => | |
rational(n * n2, d * d2), | |
div: ({ numerator: n2, denominator: d2 }: Rational) => | |
rational(n, d).mul(rational(d2, n2)), | |
valueOf: () => n / d, | |
toString: () => `${n}/${d}`, | |
}); | |
const gcd = (a: number, b: number): number => b === 0 ? a : gcd(b, a % b); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment