flatten-into-array.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. var isArray = require('../internals/is-array');
  3. var lengthOfArrayLike = require('../internals/length-of-array-like');
  4. var doesNotExceedSafeInteger = require('../internals/does-not-exceed-safe-integer');
  5. var bind = require('../internals/function-bind-context');
  6. // `FlattenIntoArray` abstract operation
  7. // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
  8. var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) {
  9. var targetIndex = start;
  10. var sourceIndex = 0;
  11. var mapFn = mapper ? bind(mapper, thisArg) : false;
  12. var element, elementLen;
  13. while (sourceIndex < sourceLen) {
  14. if (sourceIndex in source) {
  15. element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
  16. if (depth > 0 && isArray(element)) {
  17. elementLen = lengthOfArrayLike(element);
  18. targetIndex = flattenIntoArray(target, original, element, elementLen, targetIndex, depth - 1) - 1;
  19. } else {
  20. doesNotExceedSafeInteger(targetIndex + 1);
  21. target[targetIndex] = element;
  22. }
  23. targetIndex++;
  24. }
  25. sourceIndex++;
  26. }
  27. return targetIndex;
  28. };
  29. module.exports = flattenIntoArray;