array-flatten.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. 'use strict'
  2. /**
  3. * Expose `arrayFlatten`.
  4. */
  5. module.exports = flatten
  6. module.exports.from = flattenFrom
  7. module.exports.depth = flattenDepth
  8. module.exports.fromDepth = flattenFromDepth
  9. /**
  10. * Flatten an array.
  11. *
  12. * @param {Array} array
  13. * @return {Array}
  14. */
  15. function flatten (array) {
  16. if (!Array.isArray(array)) {
  17. throw new TypeError('Expected value to be an array')
  18. }
  19. return flattenFrom(array)
  20. }
  21. /**
  22. * Flatten an array-like structure.
  23. *
  24. * @param {Array} array
  25. * @return {Array}
  26. */
  27. function flattenFrom (array) {
  28. return flattenDown(array, [])
  29. }
  30. /**
  31. * Flatten an array-like structure with depth.
  32. *
  33. * @param {Array} array
  34. * @param {number} depth
  35. * @return {Array}
  36. */
  37. function flattenDepth (array, depth) {
  38. if (!Array.isArray(array)) {
  39. throw new TypeError('Expected value to be an array')
  40. }
  41. return flattenFromDepth(array, depth)
  42. }
  43. /**
  44. * Flatten an array-like structure with depth.
  45. *
  46. * @param {Array} array
  47. * @param {number} depth
  48. * @return {Array}
  49. */
  50. function flattenFromDepth (array, depth) {
  51. if (typeof depth !== 'number') {
  52. throw new TypeError('Expected the depth to be a number')
  53. }
  54. return flattenDownDepth(array, [], depth)
  55. }
  56. /**
  57. * Flatten an array indefinitely.
  58. *
  59. * @param {Array} array
  60. * @param {Array} result
  61. * @return {Array}
  62. */
  63. function flattenDown (array, result) {
  64. for (var i = 0; i < array.length; i++) {
  65. var value = array[i]
  66. if (Array.isArray(value)) {
  67. flattenDown(value, result)
  68. } else {
  69. result.push(value)
  70. }
  71. }
  72. return result
  73. }
  74. /**
  75. * Flatten an array with depth.
  76. *
  77. * @param {Array} array
  78. * @param {Array} result
  79. * @param {number} depth
  80. * @return {Array}
  81. */
  82. function flattenDownDepth (array, result, depth) {
  83. depth--
  84. for (var i = 0; i < array.length; i++) {
  85. var value = array[i]
  86. if (depth > -1 && Array.isArray(value)) {
  87. flattenDownDepth(value, result, depth)
  88. } else {
  89. result.push(value)
  90. }
  91. }
  92. return result
  93. }