-
-
Save ccnixon/4d28e096a93232208240 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