es6.number.constructor.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var $ = require('./$')
  3. , global = require('./$.global')
  4. , has = require('./$.has')
  5. , cof = require('./$.cof')
  6. , toPrimitive = require('./$.to-primitive')
  7. , fails = require('./$.fails')
  8. , $trim = require('./$.string-trim').trim
  9. , NUMBER = 'Number'
  10. , $Number = global[NUMBER]
  11. , Base = $Number
  12. , proto = $Number.prototype
  13. // Opera ~12 has broken Object#toString
  14. , BROKEN_COF = cof($.create(proto)) == NUMBER
  15. , TRIM = 'trim' in String.prototype;
  16. // 7.1.3 ToNumber(argument)
  17. var toNumber = function(argument){
  18. var it = toPrimitive(argument, false);
  19. if(typeof it == 'string' && it.length > 2){
  20. it = TRIM ? it.trim() : $trim(it, 3);
  21. var first = it.charCodeAt(0)
  22. , third, radix, maxCode;
  23. if(first === 43 || first === 45){
  24. third = it.charCodeAt(2);
  25. if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
  26. } else if(first === 48){
  27. switch(it.charCodeAt(1)){
  28. case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
  29. case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
  30. default : return +it;
  31. }
  32. for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
  33. code = digits.charCodeAt(i);
  34. // parseInt parses a string to a first unavailable symbol
  35. // but ToNumber should return NaN if a string contains unavailable symbols
  36. if(code < 48 || code > maxCode)return NaN;
  37. } return parseInt(digits, radix);
  38. }
  39. } return +it;
  40. };
  41. if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
  42. $Number = function Number(value){
  43. var it = arguments.length < 1 ? 0 : value
  44. , that = this;
  45. return that instanceof $Number
  46. // check on 1..constructor(foo) case
  47. && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
  48. ? new Base(toNumber(it)) : toNumber(it);
  49. };
  50. $.each.call(require('./$.descriptors') ? $.getNames(Base) : (
  51. // ES3:
  52. 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
  53. // ES6 (in case, if modules with ES6 Number statics required before):
  54. 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
  55. 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
  56. ).split(','), function(key){
  57. if(has(Base, key) && !has($Number, key)){
  58. $.setDesc($Number, key, $.getDesc(Base, key));
  59. }
  60. });
  61. $Number.prototype = proto;
  62. proto.constructor = $Number;
  63. require('./$.redefine')(global, NUMBER, $Number);
  64. }