Skip to content

Commit 7eb7998

Browse files
authored
fix(NODE-3390): serialize non-finite doubles correctly in EJSON (#445)
1 parent 804050d commit 7eb7998

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/extended_json.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ function serializeValue(value: any, options: EJSONSerializeOptions): any {
213213
: { $date: { $numberLong: value.getTime().toString() } };
214214
}
215215

216-
if (typeof value === 'number' && !options.relaxed) {
216+
if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
217217
// it's an integer
218218
if (Math.floor(value) === value) {
219219
const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,

test/node/extended_json_tests.js

+9
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,15 @@ describe('Extended JSON', function () {
168168
expect(serialized).to.equal('42');
169169
});
170170

171+
it('should correctly serialize non-finite numbers', function () {
172+
const numbers = { neginf: -Infinity, posinf: Infinity, nan: NaN };
173+
const serialized = EJSON.stringify(numbers);
174+
expect(serialized).to.equal(
175+
'{"neginf":{"$numberDouble":"-Infinity"},"posinf":{"$numberDouble":"Infinity"},"nan":{"$numberDouble":"NaN"}}'
176+
);
177+
expect(EJSON.parse(serialized)).to.deep.equal(numbers);
178+
});
179+
171180
it('should correctly parse null values', function () {
172181
expect(EJSON.parse('null')).to.be.null;
173182
expect(EJSON.parse('[null]')[0]).to.be.null;

0 commit comments

Comments
 (0)