FlattenIntoArray.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // eslint-disable-next-line max-params
  14. module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) {
  15. var mapperFunction;
  16. if (arguments.length > 5) {
  17. mapperFunction = arguments[5];
  18. }
  19. var targetIndex = start;
  20. var sourceIndex = 0;
  21. while (sourceIndex < sourceLen) {
  22. var P = ToString(sourceIndex);
  23. var exists = HasProperty(source, P);
  24. if (exists === true) {
  25. var element = Get(source, P);
  26. if (typeof mapperFunction !== 'undefined') {
  27. if (arguments.length <= 6) {
  28. throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
  29. }
  30. element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
  31. }
  32. var shouldFlatten = false;
  33. if (depth > 0) {
  34. shouldFlatten = IsArray(element);
  35. }
  36. if (shouldFlatten) {
  37. var elementLen = ToLength(Get(element, 'length'));
  38. targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
  39. } else {
  40. if (targetIndex >= MAX_SAFE_INTEGER) {
  41. throw new $TypeError('index too large');
  42. }
  43. CreateDataPropertyOrThrow(target, ToString(targetIndex), element);
  44. targetIndex += 1;
  45. }
  46. }
  47. sourceIndex += 1;
  48. }
  49. return targetIndex;
  50. };