Skip to content

Instantly share code, notes, and snippets.

@JonathanGawrych
Last active March 18, 2024 01:46
Show Gist options
  • Save JonathanGawrych/e687acc50f1d40fe5982da788983dc89 to your computer and use it in GitHub Desktop.
Save JonathanGawrych/e687acc50f1d40fe5982da788983dc89 to your computer and use it in GitHub Desktop.
Given an key of a deep object and you're trying to find a path to it, BFS and print the path
const findPathByKey = (ob, key) => {
const found = new Set();
const queue = [{obj: ob, path: []}];
let pathLength = 0;
while (queue.length > 0) {
const {obj, path} = queue.shift();
if (pathLength < path.length) {
pathLength = path.length;
console.log(`increasing depth to ${pathLength}, current queue size: ${queue.length}, current found size: ${found.size}`);
}
if (path[path.length - 1] === key) {
console.log(path.join('.'));
continue;
}
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function' && !Array.isArray(obj)) || obj instanceof SVGLength) {
continue;
}
else if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
if (!found.has(obj[i])) {
queue.push({obj: obj[i], path: [...path, i]});
found.add(obj[i]);
}
}
}
else {
for (const k in obj) {
try {
if (!found.has(obj[k])) {
queue.push({obj: obj[k], path: [...path, k]});
found.add(obj[k]);
}
} catch (e) { }
}
}
}
console.log('done');
}
const findPathByValue = (ob, value) => {
const found = new Set();
const queue = [{obj: ob, path: []}];
let pathLength = 0;
while (queue.length > 0) {
const {obj, path} = queue.shift();
if (pathLength < path.length) {
pathLength = path.length;
console.log(`increasing depth to ${pathLength}, current queue size: ${queue.length}, current found size: ${found.size}`);
}
if (obj === value) {
console.log(path.join('.'));
continue;
}
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function' && !Array.isArray(obj)) || obj instanceof SVGLength) {
continue;
}
else if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
if (!found.has(obj[i])) {
queue.push({obj: obj[i], path: [...path, i]});
found.add(obj[i]);
}
}
}
else {
for (const k in obj) {
try {
if (!found.has(obj[k])) {
queue.push({obj: obj[k], path: [...path, k]});
found.add(obj[k]);
}
} catch (e) { }
}
}
}
console.log('done');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment