Skip to content

Commit

Permalink
casted
Browse files Browse the repository at this point in the history
  • Loading branch information
aditi-khare-mongoDB committed Nov 12, 2024
1 parent 727ca14 commit c88c52e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
1 change: 0 additions & 1 deletion docs/schematypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,6 @@ The values `null` and `undefined` are not cast.
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:

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

Expand Down
52 changes: 52 additions & 0 deletions lib/cast/double.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
'use strict';

const assert = require('assert');
const BSON = require('bson');

/**
* Given a value, cast it to a IEEE 754-2008 floating point, or throw an `Error` if the value
* cannot be casted. `null`, `undefined`, and `NaN` are considered valid inputs.
*
* @param {Any} value
* @return {Number}
* @throws {Error} if `value` does not represent a IEEE 754-2008 floating point. If casting from a string, see BSON Double.fromString API documentation
* @api private
*/

module.exports = function castDouble(val) {
if (val == null) {
return val;
}
if (val === '') {
return null;
}

let coercedVal;
if (val instanceof BSON.Int32 || val instanceof BSON.Double) {
coercedVal = val.value;
} else if (val instanceof BSON.Long) {
coercedVal = val.toNumber();
} else if (typeof val === 'string') {
try {
coercedVal = BSON.Double.fromString(val);
} catch {
assert.ok(false);
}
} else if (typeof val === 'object') {
const tempVal = val.valueOf() ?? val.toString();
// ex: { a: 'im an object, valueOf: () => 'helloworld' } // throw an error
if (typeof tempVal === 'string') {
try {
coercedVal = BSON.Double.fromString(val);
} catch {
assert.ok(false);
}
} else {
coercedVal = Number(tempVal);
}
} {
coercedVal = Number(val);
}

return coercedVal;
};

0 comments on commit c88c52e

Please sign in to comment.