Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active August 26, 2023 10:02
Show Gist options
  • Save jfet97/503ca3a4a2c379413b7722a46228483a to your computer and use it in GitHub Desktop.
Save jfet97/503ca3a4a2c379413b7722a46228483a to your computer and use it in GitHub Desktop.
Simple Depth First Search in JavaScript
function isObject(entity) {
return typeof entity === "object" && entity !== null;
}
function getAdjacentNodes(obj) {
return (
Object.entries(obj)
.filter(([, v]) => isObject(v))
)
}
function safePrint(obj) {
console.log(
JSON.stringify(
obj,
function (key, value) {
const isVObject = isObject(value);
const isNode = isVObject && key === "";
if(isNode || !isVObject) return value;
else return key;
},
4
)
);
}
function _DFS(node, visitedNodes) {
if(visitedNodes.has(node)) {
return;
}
safePrint(node);
visitedNodes.add(node, true);
for (const [, n] of getAdjacentNodes(node)) {
_DFS(n, visitedNodes);
}
}
function DFS(obj) {
return _DFS(obj, new Set());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment