flatten-into-array.js 1.1 KB

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