_flatten.js 1016 B

1234567891011121314151617181920212223242526272829303132
  1. define(['./_getLength', './_isArrayLike', './isArray', './isArguments'], function (_getLength, _isArrayLike, isArray, isArguments) {
  2. // Internal implementation of a recursive `flatten` function.
  3. function flatten(input, depth, strict, output) {
  4. output = output || [];
  5. if (!depth && depth !== 0) {
  6. depth = Infinity;
  7. } else if (depth <= 0) {
  8. return output.concat(input);
  9. }
  10. var idx = output.length;
  11. for (var i = 0, length = _getLength(input); i < length; i++) {
  12. var value = input[i];
  13. if (_isArrayLike(value) && (isArray(value) || isArguments(value))) {
  14. // Flatten current level of array or arguments object.
  15. if (depth > 1) {
  16. flatten(value, depth - 1, strict, output);
  17. idx = output.length;
  18. } else {
  19. var j = 0, len = value.length;
  20. while (j < len) output[idx++] = value[j++];
  21. }
  22. } else if (!strict) {
  23. output[idx++] = value;
  24. }
  25. }
  26. return output;
  27. }
  28. return flatten;
  29. });