int32.js 848 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const isBsonType = require('../helpers/isBsonType');
  3. const assert = require('assert');
  4. /**
  5. * Given a value, cast it to a Int32, or throw an `Error` if the value
  6. * cannot be casted. `null` and `undefined` are considered valid.
  7. *
  8. * @param {Any} value
  9. * @return {Number}
  10. * @throws {Error} if `value` does not represent an integer, or is outside the bounds of an 32-bit integer.
  11. * @api private
  12. */
  13. module.exports = function castInt32(val) {
  14. if (val == null) {
  15. return val;
  16. }
  17. if (val === '') {
  18. return null;
  19. }
  20. const coercedVal = isBsonType(val, 'Long') ? val.toNumber() : Number(val);
  21. const INT32_MAX = 0x7FFFFFFF;
  22. const INT32_MIN = -0x80000000;
  23. if (coercedVal === (coercedVal | 0) &&
  24. coercedVal >= INT32_MIN &&
  25. coercedVal <= INT32_MAX
  26. ) {
  27. return coercedVal;
  28. }
  29. assert.ok(false);
  30. };