Last active
October 10, 2015 15:39
-
-
Save bonpixel/d0d66dced6d6b10dc50c to your computer and use it in GitHub Desktop.
Recursion Example
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
/** | |
* 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] | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)