ToInt32.js 688 B

1234567891011121314151617181920212223
  1. 'use strict';
  2. var modulo = require('./modulo');
  3. var ToNumber = require('./ToNumber');
  4. var truncate = require('./truncate');
  5. var isFinite = require('../helpers/isFinite');
  6. // https://262.ecma-international.org/14.0/#sec-toint32
  7. var two31 = 0x80000000; // Math.pow(2, 31);
  8. var two32 = 0x100000000; // Math.pow(2, 32);
  9. module.exports = function ToInt32(argument) {
  10. var number = ToNumber(argument);
  11. if (!isFinite(number) || number === 0) {
  12. return 0;
  13. }
  14. var int = truncate(number);
  15. var int32bit = modulo(int, two32);
  16. var result = int32bit >= two31 ? int32bit - two32 : int32bit;
  17. return result === 0 ? 0 : result; // in the spec, these are math values, so we filter out -0 here
  18. };