FlattenIntoArray.js 1.7 KB

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