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