Skip to content

Instantly share code, notes, and snippets.

@mkropat
Created September 20, 2019 15:20
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 mkropat/ecbe3ab6955a2688534217cd9ab9e58d to your computer and use it in GitHub Desktop.
Save mkropat/ecbe3ab6955a2688534217cd9ab9e58d to your computer and use it in GitHub Desktop.
function traverseLevelOrder(thing, predicate, maxDepth=20) {
function traverse(thing, predicate, targetDepth, depth=0) {
if (targetDepth !== depth) {
for (const key in thing) {
const val = traverse(thing[key], predicate, targetDepth, depth + 1);
if (val) {
return val;
}
}
return;
}
for (const key in thing) {
if (predicate(thing[key])) {
return thing[key];
}
}
}
for (let i = 0; i < maxDepth; i++) {
const val = traverse(thing, predicate, i);
if (val) {
return val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment