Created
January 26, 2012 00:16
-
-
Save inez/1679950 to your computer and use it in GitHub Desktop.
Depth first stack iterator in JavaScript
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
var data = ["a","b",["b1","b2","b3",["c1","c2"]],"c",["c1","c2"]]; | |
var traverse = function(data, callback) { | |
var current = [data, 0]; | |
var stack = [current]; | |
while(stack.length > 0) { | |
if(current[1] >= current[0].length) { | |
stack.pop(); | |
current = stack[stack.length-1]; | |
continue; | |
} | |
var item = current[0][current[1]]; | |
if($.isArray(item) && item.length > 0) { | |
stack.push([item,0]); | |
current[1]++; | |
current = stack[stack.length-1]; | |
continue; | |
} | |
if(callback(item) === false) { | |
return; | |
} | |
current[1]++; | |
} | |
}; | |
traverse(data, function(item) { | |
console.log(item); | |
if(item === "c") { | |
// stop on element "c" | |
return false; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment