number.js 911 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const assert = require('assert');
  3. /*!
  4. * Given a value, cast it to a number, or throw an `Error` if the value
  5. * cannot be casted. `null` and `undefined` are considered valid.
  6. *
  7. * @param {Any} value
  8. * @return {Number}
  9. * @throws {Error} if `value` is not one of the allowed values
  10. * @api private
  11. */
  12. module.exports = function castNumber(val) {
  13. if (val == null) {
  14. return val;
  15. }
  16. if (val === '') {
  17. return null;
  18. }
  19. if (typeof val === 'string' || typeof val === 'boolean') {
  20. val = Number(val);
  21. }
  22. assert.ok(!isNaN(val));
  23. if (val instanceof Number) {
  24. return val.valueOf();
  25. }
  26. if (typeof val === 'number') {
  27. return val;
  28. }
  29. if (!Array.isArray(val) && typeof val.valueOf === 'function') {
  30. return Number(val.valueOf());
  31. }
  32. if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) {
  33. return Number(val);
  34. }
  35. assert.ok(false);
  36. };