Skip to content

Commit c88c52e

Browse files
casted
1 parent 727ca14 commit c88c52e

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

docs/schematypes.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -682,7 +682,6 @@ The values `null` and `undefined` are not cast.
682682
The following inputs will result will all result in a [CastError](validation.html#cast-errors) once validated, meaning that it will not throw on initialization, only when validated:
683683

684684
* strings that do not represent a numeric string, a NaN or a null-ish value
685-
* numbers in non-decimal or exponential format
686685
* objects that don't have a `valueOf()` function
687686
* an input that represents a value outside the bounds of a IEEE 754-2008 floating point
688687

lib/cast/double.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
3+
const assert = require('assert');
4+
const BSON = require('bson');
5+
6+
/**
7+
* Given a value, cast it to a IEEE 754-2008 floating point, or throw an `Error` if the value
8+
* cannot be casted. `null`, `undefined`, and `NaN` are considered valid inputs.
9+
*
10+
* @param {Any} value
11+
* @return {Number}
12+
* @throws {Error} if `value` does not represent a IEEE 754-2008 floating point. If casting from a string, see BSON Double.fromString API documentation
13+
* @api private
14+
*/
15+
16+
module.exports = function castDouble(val) {
17+
if (val == null) {
18+
return val;
19+
}
20+
if (val === '') {
21+
return null;
22+
}
23+
24+
let coercedVal;
25+
if (val instanceof BSON.Int32 || val instanceof BSON.Double) {
26+
coercedVal = val.value;
27+
} else if (val instanceof BSON.Long) {
28+
coercedVal = val.toNumber();
29+
} else if (typeof val === 'string') {
30+
try {
31+
coercedVal = BSON.Double.fromString(val);
32+
} catch {
33+
assert.ok(false);
34+
}
35+
} else if (typeof val === 'object') {
36+
const tempVal = val.valueOf() ?? val.toString();
37+
// ex: { a: 'im an object, valueOf: () => 'helloworld' } // throw an error
38+
if (typeof tempVal === 'string') {
39+
try {
40+
coercedVal = BSON.Double.fromString(val);
41+
} catch {
42+
assert.ok(false);
43+
}
44+
} else {
45+
coercedVal = Number(tempVal);
46+
}
47+
} {
48+
coercedVal = Number(val);
49+
}
50+
51+
return coercedVal;
52+
};

0 commit comments

Comments
 (0)