Skip to content

Instantly share code, notes, and snippets.

@goatslacker
Created September 9, 2011 00:12
Show Gist options
  • Save goatslacker/1205159 to your computer and use it in GitHub Desktop.
Save goatslacker/1205159 to your computer and use it in GitHub Desktop.
depth first search
var dfs = {
a: 1,
b: {
c: 2,
d: 3,
e: 4,
f: {
g: 5,
h: 6
},
i: 7
},
j: {
k: 8,
l: 9,
m: {
n: {
o: {
p: 10
}
},
q: 11
},
r: 12,
s: 13
},
t: 14,
u: 15,
v: {
w: 16,
x: 17,
y: {
z: 18
}
}
};
var Iterator = function (tree) {
this.tree = tree;
this.flatArray = [];
this.ct = -1;
};
Iterator.prototype.flatten = function (tree) {
tree = tree || this.tree;
Object.keys(tree).forEach(function (node) {
var obj = {};
if (typeof tree[node] === "object") {
this.flatten(tree[node]);
} else {
obj[node] = tree[node];
this.flatArray.push(obj);
}
}.bind(this));
};
Iterator.prototype.next = function () {
if (this.flatArray.length === 0) {
this.flatten();
}
this.ct += 1;
return this.ct < this.flatArray.length ? this.flatArray[this.ct] : null;
};
var tree = new Iterator(dfs);
for (var i = 0; i < 25; i += 1) {
console.log(tree.next());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment