Skip to content

Instantly share code, notes, and snippets.

@bonpixel
Last active October 10, 2015 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bonpixel/d0d66dced6d6b10dc50c to your computer and use it in GitHub Desktop.
Save bonpixel/d0d66dced6d6b10dc50c to your computer and use it in GitHub Desktop.
Recursion Example
/**
* A Little example of recursion
**/
(function(){
var flatten = function(toFlatten){
var flatArr = [],
result,
tmp;
if (typeof(toFlatten) !== 'undefined' && toFlatten instanceof Array){
for(var i = 0; i < toFlatten.length; ++i){
if(toFlatten[i] instanceof Array){
tmp = flatArr;
result = tmp.concat(flatten(toFlatten[i]));
flatArr = result;
} else {
flatArr.push(toFlatten[i]);
result = flatArr;
}
}
} else {
return null;
}
return result;
}
console.log( flatten( [1,2,3,4,5,6] ) ); //-> [1, 2, 3, 4, 5, 6]
console.log( flatten( [1,2,3,4,5,6, [1] ] ) ); //-> [1, 2, 3, 4, 5, 6, 1]
console.log( flatten( [ {}, [1,2,3,4,5,6] ] ) ); //-> [Object, 1, 2, 3, 4, 5, 6]
console.log( flatten( [ [1], [1,2,3] ] ) ); //-> [1, 1, 2, 3]
console.log( flatten( [ [1], [1,2,3], [1] ] ) ); //-> [1, 1, 2, 3, 1]
console.log( flatten( [ [1,[1,2,3,[1,2,3,[1,2,3]]]], [1,2,3], [1] ] ) ); //-> [1, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
console.log( flatten( [ ['a',['b',2,3,['c',2,3,[true,2,3]]]], [1,2,3], [1] ] ) ); //-> ["a", "b", 2, 3, "c", 2, 3, true, 2, 3, 1, 2, 3, 1]
console.log( flatten( [ ['a',['b',2,3,['c',2,3,[true,2,3]]]], [1,(function(){return false;})(),3], [1] ] ) ); //-> ["a", "b", 2, 3, "c", 2, 3, true, 2, 3, 1, false, 3, 1]
})();
@bonpixel
Copy link
Author

Here is a little example of recursion that I cooked up. It will take an array with N nested arrays and flatten them. The contents of those arrays can be anything. One way to test this code would simply be to copy and paste the code into the Chrome Developer Tools and observe the output :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment