Created
September 7, 2015 21:02
-
-
Save ashishpuliyel/b84269bace62b2a905ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
In ruby I could just do: | |
our_arr = in_arr.flatten | |
But that says more about ruby than it does about me. | |
*/ | |
/* flatten returns a new array that is a flattened | |
* version of the array passed in, runs recursively. | |
* | |
* inArr - The array to be flattened | |
*/ | |
function flatten(inArr) { | |
var outArr = []; | |
inArr.forEach(function(el) { | |
/* Array.isArray is an ES5 feature */ | |
if (Array.isArray(el)) { | |
outArr = outArr.concat(flatten(el)); | |
} else { | |
outArr.push(el); | |
} | |
}); | |
return outArr; | |
} | |
/* I'm provding a function here that tests/demonstrates the flatten function above. | |
* Returns a boolean indicating the test pass status. */ | |
function testFlatten() { | |
//tests is an array of objects, each with an input and an expected output | |
var tests = [{ | |
input : [[1,2,[3]],4], | |
expected : [1,2,3,4] | |
}, { | |
input : [[]], | |
expected : [] | |
}, { | |
input : [1,2,3,[3],1,[1,[2,[3,3,[[3]]]]]], | |
expected : [1,2,3,3,1,1,2,3,3,3] | |
}]; | |
var passed = true; | |
tests.forEach(function(test, i) { | |
//This comparison technique works for comparing 1-d arrays of integers. | |
if (JSON.stringify(flatten(test.input)) === JSON.stringify(test.expected)) { | |
console.log("Test Passed:", i+1); | |
} else { | |
console.log("Test Failed:", i+1); | |
passed = false; | |
} | |
}); | |
return passed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment