blob: 6429ee797f9bfb3ed93585f9f4319a4e48bdcaf3 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var GetIntrinsic = require('get-intrinsic');
4
5var $TypeError = GetIntrinsic('%TypeError%');
6
7var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
8
9var Call = require('./Call');
10var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow');
11var Get = require('./Get');
12var HasProperty = require('./HasProperty');
13var IsArray = require('./IsArray');
14var LengthOfArrayLike = require('./LengthOfArrayLike');
15var ToString = require('./ToString');
16
17// https://262.ecma-international.org/11.0/#sec-flattenintoarray
18
19// eslint-disable-next-line max-params
20module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) {
21 var mapperFunction;
22 if (arguments.length > 5) {
23 mapperFunction = arguments[5];
24 }
25
26 var targetIndex = start;
27 var sourceIndex = 0;
28 while (sourceIndex < sourceLen) {
29 var P = ToString(sourceIndex);
30 var exists = HasProperty(source, P);
31 if (exists === true) {
32 var element = Get(source, P);
33 if (typeof mapperFunction !== 'undefined') {
34 if (arguments.length <= 6) {
35 throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
36 }
37 element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
38 }
39 var shouldFlatten = false;
40 if (depth > 0) {
41 shouldFlatten = IsArray(element);
42 }
43 if (shouldFlatten) {
44 var elementLen = LengthOfArrayLike(element);
45 targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
46 } else {
47 if (targetIndex >= MAX_SAFE_INTEGER) {
48 throw new $TypeError('index too large');
49 }
50 CreateDataPropertyOrThrow(target, ToString(targetIndex), element);
51 targetIndex += 1;
52 }
53 }
54 sourceIndex += 1;
55 }
56
57 return targetIndex;
58};