_flatten-into-array.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
  3. var isArray = require('./_is-array');
  4. var isObject = require('./_is-object');
  5. var toLength = require('./_to-length');
  6. var ctx = require('./_ctx');
  7. var IS_CONCAT_SPREADABLE = require('./_wks')('isConcatSpreadable');
  8. function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
  9. var targetIndex = start;
  10. var sourceIndex = 0;
  11. var mapFn = mapper ? ctx(mapper, thisArg, 3) : false;
  12. var element, spreadable;
  13. while (sourceIndex < sourceLen) {
  14. if (sourceIndex in source) {
  15. element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
  16. spreadable = false;
  17. if (isObject(element)) {
  18. spreadable = element[IS_CONCAT_SPREADABLE];
  19. spreadable = spreadable !== undefined ? !!spreadable : isArray(element);
  20. }
  21. if (spreadable && depth > 0) {
  22. targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
  23. } else {
  24. if (targetIndex >= 0x1fffffffffffff) throw TypeError();
  25. target[targetIndex] = element;
  26. }
  27. targetIndex++;
  28. }
  29. sourceIndex++;
  30. }
  31. return targetIndex;
  32. }
  33. module.exports = flattenIntoArray;