Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This is 'gentle' way of traversing an array
- * and flatten it if it has multiple arrays.
- * We chose not to use function reduce becuase
- * we want ours to be intuitive.
- */
- function flat(arr) {
- 'use strict';
- var acc = [], elem;
- while (typeof arr !== 'undefined' && Array.isArray(arr) && arr.length > 0) {
- elem = arr.shift();
- //ternary used because it is an expression
- acc = acc.concat(Array.isArray(elem) ? flat(elem) : elem);
- }
- return acc;
- }
- /**
- * This test would not work for arrays that
- * have objects. It is tested with string and number
- */
- function testArrayEql(arr1, arr2) {
- 'use strict';
- var len = arr1.length, i;
- if (len === arr2.length) {
- for (i = 0; i < len; i++) {
- if (arr1[i] !== arr2[i]) {
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
- }
- function testFlat(arr1, arr2) {
- 'use strict';
- var flattenArr = flat(arr1);
- if (!testArrayEql(flattenArr, arr2)) {
- console.log("Flatten test failed the two arrays are not equal", flattenArr, ", ", arr2);
- } else {
- console.log("Flatten test succeeded the two arrays are equal", flattenArr, ", ", arr2);
- }
- }
- testFlat([[0, 1], [2, 3], [4, 5]], [0, 1, 2, 3, 4, 5]);
- testFlat([0, [1, [2, [3, [4, [5]]]]]], [0, 1, 2, 3, 4, 5]);
- testFlat([[1, 2, [3]], 4], [1, 2, 3, 4]);
- testFlat([["first", 2, ["second"]], "last"], ["first", 2, "second", "last"]);
- testFlat([[0, 1], [2, 3, 3], [4, 5]], [0, 1, 2, 3, 4, 5]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement