array-flatten.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict'
  2. /**
  3. * Expose `arrayFlatten`.
  4. */
  5. module.exports = arrayFlatten
  6. /**
  7. * Recursive flatten function with depth.
  8. *
  9. * @param {Array} array
  10. * @param {Array} result
  11. * @param {Number} depth
  12. * @return {Array}
  13. */
  14. function flattenWithDepth (array, result, depth) {
  15. for (var i = 0; i < array.length; i++) {
  16. var value = array[i]
  17. if (depth > 0 && Array.isArray(value)) {
  18. flattenWithDepth(value, result, depth - 1)
  19. } else {
  20. result.push(value)
  21. }
  22. }
  23. return result
  24. }
  25. /**
  26. * Recursive flatten function. Omitting depth is slightly faster.
  27. *
  28. * @param {Array} array
  29. * @param {Array} result
  30. * @return {Array}
  31. */
  32. function flattenForever (array, result) {
  33. for (var i = 0; i < array.length; i++) {
  34. var value = array[i]
  35. if (Array.isArray(value)) {
  36. flattenForever(value, result)
  37. } else {
  38. result.push(value)
  39. }
  40. }
  41. return result
  42. }
  43. /**
  44. * Flatten an array, with the ability to define a depth.
  45. *
  46. * @param {Array} array
  47. * @param {Number} depth
  48. * @return {Array}
  49. */
  50. function arrayFlatten (array, depth) {
  51. if (depth == null) {
  52. return flattenForever(array, [])
  53. }
  54. return flattenWithDepth(array, [], depth)
  55. }