flatten.js 963 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Stack grow safe implementation
  2. "use strict";
  3. var ensureValue = require("../../object/valid-value")
  4. , isArray = Array.isArray
  5. , objHasOwnProperty = Object.prototype.hasOwnProperty;
  6. module.exports = function () {
  7. var input = ensureValue(this), index = 0, remaining, remainingIndexes, length, i, result = [];
  8. // Jslint: ignore
  9. main: while (input) {
  10. length = input.length;
  11. for (i = index; i < length; ++i) {
  12. if (!objHasOwnProperty.call(input, i)) continue;
  13. if (isArray(input[i])) {
  14. if (i < length - 1) {
  15. // eslint-disable-next-line max-depth
  16. if (!remaining) {
  17. remaining = [];
  18. remainingIndexes = [];
  19. }
  20. remaining.push(input);
  21. remainingIndexes.push(i + 1);
  22. }
  23. input = input[i];
  24. index = 0;
  25. continue main;
  26. }
  27. result.push(input[i]);
  28. }
  29. if (remaining) {
  30. input = remaining.pop();
  31. index = remainingIndexes.pop();
  32. } else {
  33. input = null;
  34. }
  35. }
  36. return result;
  37. };