flatten.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var isArray = require('../lang/isArray');
  2. var append = require('./append');
  3. /*
  4. * Helper function to flatten to a destination array.
  5. * Used to remove the need to create intermediate arrays while flattening.
  6. */
  7. function flattenTo(arr, result, level) {
  8. if (arr == null) {
  9. return result;
  10. } else if (level === 0) {
  11. append(result, arr);
  12. return result;
  13. }
  14. var value,
  15. i = -1,
  16. len = arr.length;
  17. while (++i < len) {
  18. value = arr[i];
  19. if (isArray(value)) {
  20. flattenTo(value, result, level - 1);
  21. } else {
  22. result.push(value);
  23. }
  24. }
  25. return result;
  26. }
  27. /**
  28. * Recursively flattens an array.
  29. * A new array containing all the elements is returned.
  30. * If `shallow` is true, it will only flatten one level.
  31. */
  32. function flatten(arr, level) {
  33. level = level == null? -1 : level;
  34. return flattenTo(arr, [], level);
  35. }
  36. module.exports = flatten;