FlattenIntoArray.js 1.6 KB

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