ArrayCreate.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $ArrayPrototype = GetIntrinsic('%Array.prototype%');
  4. var $RangeError = GetIntrinsic('%RangeError%');
  5. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  6. var $TypeError = GetIntrinsic('%TypeError%');
  7. var IsInteger = require('./IsInteger');
  8. var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1;
  9. var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || (
  10. // eslint-disable-next-line no-proto, no-negated-condition
  11. [].__proto__ !== $ArrayPrototype
  12. ? null
  13. : function (O, proto) {
  14. O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign
  15. return O;
  16. }
  17. );
  18. // https://ecma-international.org/ecma-262/6.0/#sec-arraycreate
  19. module.exports = function ArrayCreate(length) {
  20. if (!IsInteger(length) || length < 0) {
  21. throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0');
  22. }
  23. if (length > MAX_ARRAY_LENGTH) {
  24. throw new $RangeError('length is greater than (2**32 - 1)');
  25. }
  26. var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype;
  27. var A = []; // steps 5 - 7, and 9
  28. if (proto !== $ArrayPrototype) { // step 8
  29. if (!$setProto) {
  30. throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]');
  31. }
  32. $setProto(A, proto);
  33. }
  34. if (length !== 0) { // bypasses the need for step 2
  35. A.length = length;
  36. }
  37. /* step 10, the above as a shortcut for the below
  38. OrdinaryDefineOwnProperty(A, 'length', {
  39. '[[Configurable]]': false,
  40. '[[Enumerable]]': false,
  41. '[[Value]]': length,
  42. '[[Writable]]': true
  43. });
  44. */
  45. return A;
  46. };