Skip to content

Commit

Permalink
Make Fraction's booleanish methods work with NaN
Browse files Browse the repository at this point in the history
ref #11
  • Loading branch information
frostburn committed Dec 9, 2023
1 parent fb0e7fa commit 7c850ba
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
30 changes: 30 additions & 0 deletions src/__tests__/fraction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
24 changes: 18 additions & 6 deletions src/fraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

/**
Expand All @@ -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;
}
}

/**
Expand All @@ -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;
}
}

/**
Expand Down

0 comments on commit 7c850ba

Please sign in to comment.