ArrayCreate.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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('../helpers/isInteger');
  8. var hasProto = require('has-proto')();
  9. var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1;
  10. var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || (
  11. hasProto
  12. ? function (O, proto) {
  13. O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign
  14. return O;
  15. }
  16. : null
  17. );
  18. // https://262.ecma-international.org/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. };