Skip to content

Commit

Permalink
Fix handling of null in Fraction reviver
Browse files Browse the repository at this point in the history
  • Loading branch information
frostburn committed May 4, 2024
1 parent e946b1f commit 9e4984e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/__tests__/fraction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -735,18 +735,19 @@ describe('JSON serialization', () => {
new Fraction('1.234'),
'hello',
new Fraction({s: 0, n: 0, d: 1}),
null,
]);

expect(serialized).toBe(
'[{"n":42,"d":1},2,{"n":-5,"d":3},{"n":617,"d":500},"hello",{"n":0,"d":1}]'
'[{"n":42,"d":1},2,{"n":-5,"d":3},{"n":617,"d":500},"hello",{"n":0,"d":1},null]'
);
});

it('can revive an array of fractions along with other data', () => {
const serialized =
'[{"n":42,"d":1},2,{"n":-5,"d":3},{"n":617,"d":500},"hello",{"n":0,"d":1}]';
'[{"n":42,"d":1},2,{"n":-5,"d":3},{"n":617,"d":500},"hello",{"n":0,"d":1},null]';
const data = JSON.parse(serialized, Fraction.reviver);
expect(data).toHaveLength(6);
expect(data).toHaveLength(7);

expect(data[0]).toBeInstanceOf(Fraction);
expect(data[0]).toEqual({s: 1, n: 42, d: 1});
Expand All @@ -763,5 +764,7 @@ describe('JSON serialization', () => {

expect(data[5]).toBeInstanceOf(Fraction);
expect(data[5]).toEqual({s: 0, n: 0, d: 1});

expect(data[6]).toBeNull();
});
});
1 change: 1 addition & 0 deletions src/fraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ export class Fraction {
static reviver(key: string, value: any) {
if (
typeof value === 'object' &&
value !== null &&
'n' in value &&
Number.isInteger(value.n) &&
'd' in value &&
Expand Down

0 comments on commit 9e4984e

Please sign in to comment.