flattenArray.js.flow 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule flattenArray
  8. * @typechecks
  9. * @flow
  10. */
  11. /**
  12. * Returns a flattened array that represents the DFS traversal of the supplied
  13. * input array. For example:
  14. *
  15. * var deep = ["a", ["b", "c"], "d", {"e": [1, 2]}, [["f"], "g"]];
  16. * var flat = flattenArray(deep);
  17. * console.log(flat);
  18. * > ["a", "b", "c", "d", {"e": [1, 2]}, "f", "g"];
  19. *
  20. * @see https://github.com/jonschlinkert/arr-flatten
  21. * @copyright 2014-2015 Jon Schlinkert
  22. * @license MIT
  23. */
  24. function flattenArray(array: Array<any>): Array<any> {
  25. const result = [];
  26. flatten(array, result);
  27. return result;
  28. }
  29. function flatten(array: Array<any>, result: Array<any>): void {
  30. let length = array.length;
  31. let ii = 0;
  32. while (length--) {
  33. const current = array[ii++];
  34. if (Array.isArray(current)) {
  35. flatten(current, result);
  36. } else {
  37. result.push(current);
  38. }
  39. }
  40. }
  41. module.exports = flattenArray;