From 9e4984e9ad46e05f3e96ef3c62705ccfe5e959e0 Mon Sep 17 00:00:00 2001 From: Lumi Pakkanen Date: Sat, 4 May 2024 20:53:46 +0300 Subject: [PATCH] Fix handling of null in Fraction reviver --- src/__tests__/fraction.spec.ts | 9 ++++++--- src/fraction.ts | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/__tests__/fraction.spec.ts b/src/__tests__/fraction.spec.ts index c872cfc..4a0fafa 100644 --- a/src/__tests__/fraction.spec.ts +++ b/src/__tests__/fraction.spec.ts @@ -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}); @@ -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(); }); }); diff --git a/src/fraction.ts b/src/fraction.ts index e640d7d..16973c6 100644 --- a/src/fraction.ts +++ b/src/fraction.ts @@ -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 &&