IntegerIndexedElementGet.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var $SyntaxError = require('es-errors/syntax');
  3. var $TypeError = require('es-errors/type');
  4. var GetValueFromBuffer = require('./GetValueFromBuffer');
  5. var IsDetachedBuffer = require('./IsDetachedBuffer');
  6. var IsInteger = require('./IsInteger');
  7. var isNegativeZero = require('../helpers/isNegativeZero');
  8. var typedArrayLength = require('typed-array-length');
  9. var typedArrayBuffer = require('typed-array-buffer');
  10. var typedArrayByteOffset = require('typed-array-byte-offset');
  11. var whichTypedArray = require('which-typed-array');
  12. var tableTAO = require('./tables/typed-array-objects');
  13. // https://262.ecma-international.org/6.0/#sec-integerindexedelementget
  14. module.exports = function IntegerIndexedElementGet(O, index) {
  15. if (typeof index !== 'number') {
  16. throw new $TypeError('`index` must be a Number'); // step 1
  17. }
  18. var arrayTypeName = whichTypedArray(O); // step 10
  19. if (!arrayTypeName) {
  20. throw new $TypeError('`O` must be a TypedArray'); // step 2
  21. }
  22. if (arrayTypeName === 'BigInt64Array' || arrayTypeName === 'BigUint64Array') {
  23. throw new $SyntaxError('BigInt64Array and BigUint64Array do not exist until ES2020');
  24. }
  25. var buffer = typedArrayBuffer(O); // step 3
  26. if (IsDetachedBuffer(buffer)) {
  27. throw new $TypeError('`O` has a detached buffer'); // step 4
  28. }
  29. if (!IsInteger(index) || isNegativeZero(index)) {
  30. return void undefined; // steps 5 - 6
  31. }
  32. var length = typedArrayLength(O); // step 7
  33. if (index < 0 || index >= length) {
  34. return void undefined; // step 8
  35. }
  36. var offset = typedArrayByteOffset(O); // step 9
  37. var elementType = tableTAO.name['$' + arrayTypeName]; // step 13
  38. var elementSize = tableTAO.size['$' + elementType]; // step 11
  39. var indexedPosition = (index * elementSize) + offset; // step 12
  40. return GetValueFromBuffer(buffer, indexedPosition, elementType); // step 14
  41. };