flatten-into-array.js 1.2 KB

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