Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }