double.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. const assert = require('assert');
  3. const BSON = require('mongodb/lib/bson');
  4. const isBsonType = require('../helpers/isBsonType');
  5. /**
  6. * Given a value, cast it to a IEEE 754-2008 floating point, or throw an `Error` if the value
  7. * cannot be casted. `null`, `undefined`, and `NaN` are considered valid inputs.
  8. *
  9. * @param {Any} value
  10. * @return {Number}
  11. * @throws {Error} if `value` does not represent a IEEE 754-2008 floating point. If casting from a string, see [BSON Double.fromString API documentation](https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Double.html#fromString)
  12. * @api private
  13. */
  14. module.exports = function castDouble(val) {
  15. if (val == null || val === '') {
  16. return null;
  17. }
  18. let coercedVal;
  19. if (isBsonType(val, 'Long')) {
  20. coercedVal = val.toNumber();
  21. } else if (typeof val === 'string') {
  22. try {
  23. coercedVal = BSON.Double.fromString(val);
  24. return coercedVal;
  25. } catch {
  26. assert.ok(false);
  27. }
  28. } else if (typeof val === 'object') {
  29. const tempVal = val.valueOf() ?? val.toString();
  30. // ex: { a: 'im an object, valueOf: () => 'helloworld' } // throw an error
  31. if (typeof tempVal === 'string') {
  32. try {
  33. coercedVal = BSON.Double.fromString(tempVal);
  34. return coercedVal;
  35. } catch {
  36. assert.ok(false);
  37. }
  38. } else {
  39. coercedVal = Number(tempVal);
  40. }
  41. } else {
  42. coercedVal = Number(val);
  43. }
  44. return new BSON.Double(coercedVal);
  45. };