number.js 998 B

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