Last active
August 26, 2023 10:02
-
-
Save jfet97/503ca3a4a2c379413b7722a46228483a to your computer and use it in GitHub Desktop.
Simple Depth First Search in JavaScript
This file contains 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 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