ToIndex.js 695 B

1234567891011121314151617181920212223242526
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $RangeError = GetIntrinsic('%RangeError%');
  4. var ToIntegerOrInfinity = require('./ToIntegerOrInfinity');
  5. var ToLength = require('./ToLength');
  6. var SameValue = require('./SameValue');
  7. // https://www.ecma-international.org/ecma-262/8.0/#sec-toindex
  8. module.exports = function ToIndex(value) {
  9. if (typeof value === 'undefined') {
  10. return 0;
  11. }
  12. var integerIndex = ToIntegerOrInfinity(value);
  13. if (integerIndex < 0) {
  14. throw new $RangeError('index must be >= 0');
  15. }
  16. var index = ToLength(integerIndex);
  17. if (!SameValue(integerIndex, index)) {
  18. throw new $RangeError('index must be >= 0 and < 2 ** 53 - 1');
  19. }
  20. return index;
  21. };