-
-
Save privatenumber/aed75e60e88c16fb3b186a372b18b680 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(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