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