Skip to content

Instantly share code, notes, and snippets.

@Kreijstal
Last active August 29, 2015 14:05
Show Gist options
  • Save Kreijstal/b66ead268e6554974d9d to your computer and use it in GitHub Desktop.
Save Kreijstal/b66ead268e6554974d9d to your computer and use it in GitHub Desktop.
Object recursive loop, detects infinite recursion
function objectLoop(obj, callback) {
if (!obj) return null;
var it, key, l, currobj = {
obj: obj,
keys: Object.keys(obj),
index: 0
},
nest = [];
mai: while (currobj) {
sec: while (currobj.index < currobj.keys.length) {
it = currobj.obj[key = currobj.keys[currobj.index++]];
if (it && typeof it == "object") {
l = nest.push(currobj);
while (l--) {
if (nest[l].obj === it) {
callback.call(currobj.obj, it, key, nest.length - 1)
currobj = nest.pop();
continue sec;
}
}
callback.call(currobj.obj, it, key, nest.length - 1, true);
currobj = {
obj: it,
keys: Object.keys(it),
index: 0
};
continue mai;
} else {
callback.call(currobj.obj, it, key, nest.length)
}
}
currobj = nest.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment