Skip to content

Instantly share code, notes, and snippets.

@jfet97

jfet97/DFS.js

Last active May 5, 2021
Embed
What would you like to do?
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