From 7c850ba4425c0b23341a99f4a5b2e0e381463a68 Mon Sep 17 00:00:00 2001 From: Lumi Pakkanen Date: Sat, 9 Dec 2023 09:33:10 +0200 Subject: [PATCH] Make Fraction's booleanish methods work with NaN ref #11 --- src/__tests__/fraction.spec.ts | 30 ++++++++++++++++++++++++++++++ src/fraction.ts | 24 ++++++++++++++++++------ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/__tests__/fraction.spec.ts b/src/__tests__/fraction.spec.ts index c79f496..c6853c5 100644 --- a/src/__tests__/fraction.spec.ts +++ b/src/__tests__/fraction.spec.ts @@ -191,4 +191,34 @@ describe('Fraction', () => { const fraction = new Fraction(5, 11); expect(fraction.toString()).toBe("0.'45'"); }); + + it('is not equal to NaN', () => { + const fraction = new Fraction(3, 2); + expect(fraction.equals(NaN)).toBe(false); + }); + + it('is not equal to garbage', () => { + const fraction = new Fraction(3, 2); + expect(fraction.equals('asdf')).toBe(false); + }); + + it("doesn't compare to NaN", () => { + const fraction = new Fraction(7, 3); + expect(fraction.compare(NaN)).toBeNaN(); + }); + + it("doesn't compare to garbage", () => { + const fraction = new Fraction(7, 3); + expect(fraction.compare('garbage')).toBeNaN(); + }); + + it('is not divisible by NaN', () => { + const fraction = new Fraction(13, 11); + expect(fraction.divisible(NaN)).toBe(false); + }); + + it('is not divisible by garbage', () => { + const fraction = new Fraction(13, 11); + expect(fraction.divisible('conquer')).toBe(false); + }); }); diff --git a/src/fraction.ts b/src/fraction.ts index 4bada93..55dc627 100644 --- a/src/fraction.ts +++ b/src/fraction.ts @@ -629,8 +629,12 @@ export class Fraction { * Ex: new Fraction("19.6").equals("98/5"); **/ compare(other: FractionValue) { - const {s, n, d} = new Fraction(other); - return this.s * this.n * d - s * n * this.d; + try { + const {s, n, d} = new Fraction(other); + return this.s * this.n * d - s * n * this.d; + } catch { + return NaN; + } } /** @@ -639,8 +643,12 @@ export class Fraction { * Ex: new Fraction("19.6").equals("98/5"); **/ equals(other: FractionValue) { - const {s, n, d} = new Fraction(other); - return this.s === s && this.n === n && this.d === d; + try { + const {s, n, d} = new Fraction(other); + return this.s === s && this.n === n && this.d === d; + } catch { + return false; + } } /** @@ -649,8 +657,12 @@ export class Fraction { * Ex: new Fraction("19.6").divisible("1.5"); */ divisible(other: FractionValue) { - other = new Fraction(other); - return !(!(other.n * this.d) || (this.n * other.d) % (other.n * this.d)); + try { + other = new Fraction(other); + return !(!(other.n * this.d) || (this.n * other.d) % (other.n * this.d)); + } catch { + return false; + } } /**