blob: 4d20e2e5e3610a5a59d1ace0cd7d7ab359d1af95 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var GetIntrinsic = require('get-intrinsic');
4
5var $ArrayPrototype = GetIntrinsic('%Array.prototype%');
6var $RangeError = GetIntrinsic('%RangeError%');
7var $SyntaxError = GetIntrinsic('%SyntaxError%');
8var $TypeError = GetIntrinsic('%TypeError%');
9
10var IsInteger = require('./IsInteger');
11
12var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1;
13
14var $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
26module.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};