You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var _require = require('../helpers/is'),
  3. isArray = _require.isArray,
  4. isObject = _require.isObject;
  5. module.exports = function flatten(depth) {
  6. var flattenDepth = depth || Infinity;
  7. var fullyFlattened = false;
  8. var collection = [];
  9. var flat = function flat(items) {
  10. collection = [];
  11. if (isArray(items)) {
  12. items.forEach(function (item) {
  13. if (isArray(item)) {
  14. collection = collection.concat(item);
  15. } else if (isObject(item)) {
  16. Object.keys(item).forEach(function (property) {
  17. collection = collection.concat(item[property]);
  18. });
  19. } else {
  20. collection.push(item);
  21. }
  22. });
  23. } else {
  24. Object.keys(items).forEach(function (property) {
  25. if (isArray(items[property])) {
  26. collection = collection.concat(items[property]);
  27. } else if (isObject(items[property])) {
  28. Object.keys(items).forEach(function (prop) {
  29. collection = collection.concat(items[prop]);
  30. });
  31. } else {
  32. collection.push(items[property]);
  33. }
  34. });
  35. }
  36. fullyFlattened = collection.filter(function (item) {
  37. return isObject(item);
  38. });
  39. fullyFlattened = fullyFlattened.length === 0;
  40. flattenDepth -= 1;
  41. };
  42. flat(this.items);
  43. while (!fullyFlattened && flattenDepth > 0) {
  44. flat(collection);
  45. }
  46. return new this.constructor(collection);
  47. };