Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. /**
  2. * This is 'gentle' way of traversing an array
  3. * and flatten it if it has multiple arrays.
  4. * We chose not to use function reduce becuase
  5. * we want ours to be intuitive.
  6. */
  7.  
  8.  
  9.  
  10. function flat(arr) {
  11. 'use strict';
  12. var acc = [], elem;
  13. while (typeof arr !== 'undefined' && Array.isArray(arr) && arr.length > 0) {
  14. elem = arr.shift();
  15. //ternary used because it is an expression
  16. acc = acc.concat(Array.isArray(elem) ? flat(elem) : elem);
  17. }
  18. return acc;
  19. }
  20.  
  21. /**
  22. * This test would not work for arrays that
  23. * have objects. It is tested with string and number
  24. */
  25.  
  26.  
  27. function testArrayEql(arr1, arr2) {
  28. 'use strict';
  29. var len = arr1.length, i;
  30. if (len === arr2.length) {
  31. for (i = 0; i < len; i++) {
  32. if (arr1[i] !== arr2[i]) {
  33. return false;
  34. }
  35. }
  36. return true;
  37.  
  38. } else {
  39. return false;
  40. }
  41. }
  42.  
  43. function testFlat(arr1, arr2) {
  44. 'use strict';
  45. var flattenArr = flat(arr1);
  46. if (!testArrayEql(flattenArr, arr2)) {
  47. console.log("Flatten test failed the two arrays are not equal", flattenArr, ", ", arr2);
  48. } else {
  49. console.log("Flatten test succeeded the two arrays are equal", flattenArr, ", ", arr2);
  50. }
  51. }
  52. testFlat([[0, 1], [2, 3], [4, 5]], [0, 1, 2, 3, 4, 5]);
  53.  
  54. testFlat([0, [1, [2, [3, [4, [5]]]]]], [0, 1, 2, 3, 4, 5]);
  55.  
  56. testFlat([[1, 2, [3]], 4], [1, 2, 3, 4]);
  57.  
  58.  
  59. testFlat([["first", 2, ["second"]], "last"], ["first", 2, "second", "last"]);
  60.  
  61. testFlat([[0, 1], [2, 3, 3], [4, 5]], [0, 1, 2, 3, 4, 5]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement