Skip to content

Instantly share code, notes, and snippets.

@inez
Created January 26, 2012 00:16
Show Gist options
  • Save inez/1679950 to your computer and use it in GitHub Desktop.
Save inez/1679950 to your computer and use it in GitHub Desktop.
Depth first stack iterator in JavaScript
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