ToNumber.js 994 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. var ToPrimitive = require('./ToPrimitive');
  3. var callBound = require('call-bind/callBound');
  4. var $replace = callBound('String.prototype.replace');
  5. var safeRegexTester = require('safe-regex-test');
  6. var isNonDecimal = safeRegexTester(/^0[ob]|^[+-]0x/);
  7. // http://262.ecma-international.org/5.1/#sec-9.3
  8. module.exports = function ToNumber(value) {
  9. var prim = ToPrimitive(value, Number);
  10. if (typeof prim !== 'string') {
  11. return +prim; // eslint-disable-line no-implicit-coercion
  12. }
  13. var trimmed = $replace(
  14. prim,
  15. // eslint-disable-next-line no-control-regex
  16. /^[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+|[ \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u0085]+$/g,
  17. ''
  18. );
  19. if (isNonDecimal(trimmed)) {
  20. return NaN;
  21. }
  22. return +trimmed; // eslint-disable-line no-implicit-coercion
  23. };