Skip to content

Instantly share code, notes, and snippets.

@privatenumber
Created February 27, 2017 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save privatenumber/aed75e60e88c16fb3b186a372b18b680 to your computer and use it in GitHub Desktop.
Save privatenumber/aed75e60e88c16fb3b186a372b18b680 to your computer and use it in GitHub Desktop.
(function BFS(obj, lookingFor, maxFinds = 100, maxDuration = 3) {
console.log('Traversing', obj, 'to find', lookingFor);
let findCount = 0;
let timedOut = false;
let queue = [[obj, '']];
setTimeout(() => (timedOut = true), maxDuration * 1000);
BFS: for (let node, path; (obj = queue.shift()) && ([node, path] = obj); ) {
for (let prop in node) {
if (timedOut) { console.log('Timed out'); break BFS; }
if (!{}.hasOwnProperty.call(node, prop) || (prop.indexOf('_') > -1)) { continue; }
if (node[prop] instanceof Element) { continue; }
if (node[prop] === lookingFor) {
console.log('Found path:', path + '.' + prop);
if (++findCount === maxFinds) { break BFS; }
}
if (['object', 'function'].includes(typeof node[prop])) {
queue.push([node[prop], path + '.' + prop]);
}
}
}
console.log('Done traversing');
})({ a: 1 }, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment