ArrayCreate.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $ArrayPrototype = GetIntrinsic('%Array.prototype%');
  4. var $RangeError = require('es-errors/range');
  5. var $SyntaxError = require('es-errors/syntax');
  6. var $TypeError = require('es-errors/type');
  7. var isInteger = require('math-intrinsics/isInteger');
  8. var MAX_ARRAY_LENGTH = require('math-intrinsics/constants/maxArrayLength');
  9. var $setProto = require('set-proto');
  10. // https://262.ecma-international.org/12.0/#sec-arraycreate
  11. module.exports = function ArrayCreate(length) {
  12. if (!isInteger(length) || length < 0) {
  13. throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0');
  14. }
  15. if (length > MAX_ARRAY_LENGTH) {
  16. throw new $RangeError('length is greater than (2**32 - 1)');
  17. }
  18. var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype;
  19. var A = []; // steps 3, 5
  20. if (proto !== $ArrayPrototype) { // step 4
  21. if (!$setProto) {
  22. 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]]');
  23. }
  24. $setProto(A, proto);
  25. }
  26. if (length !== 0) { // bypasses the need for step 6
  27. A.length = length;
  28. }
  29. /* step 6, the above as a shortcut for the below
  30. OrdinaryDefineOwnProperty(A, 'length', {
  31. '[[Configurable]]': false,
  32. '[[Enumerable]]': false,
  33. '[[Value]]': length,
  34. '[[Writable]]': true
  35. });
  36. */
  37. return A;
  38. };