Skip to content

Instantly share code, notes, and snippets.

@danyg
Created January 5, 2023 15:41
Show Gist options
  • Save danyg/9fbb491b1e440e2dc06cbc6e4af5eeaf to your computer and use it in GitHub Desktop.
Save danyg/9fbb491b1e440e2dc06cbc6e4af5eeaf to your computer and use it in GitHub Desktop.
DEBUG TOOL: whereTheHeckIs
/**
* - Open Chrome Dev tools
* - Go To Sources
* - in the left side, go to Snippets
* - add new snippet
* - paste this code
* - save and execute
* - > whereTheHeckIs(store.getState(), 'stringToSearch');
*/
(() => {
const isObject = (theObject) => theObject instanceof Object;
/**
* @param {{[key: string]: unknown} | unknown[]} objectTree
* @param {string|number} searchTerm
* @param {string} currPath
* @return string[]
**/
const whereTheHeckIs = (
objectTree,
searchTerm,
currPath = "",
maxDepth = 8
) => {
if (maxDepth < 0) return [];
if (Array.isArray(objectTree))
return whereArray(objectTree, searchTerm, currPath);
/** @type string[] */
let searchFindings = [];
Object.entries(objectTree).forEach(([key, data]) => {
/** @type string */
const currentPath = `${currPath}${parseInt(key) ? `[${key}]` : `.${key}`}`;
if (isObject(data)) {
searchFindings = searchFindings.concat(
whereTheHeckIs(data, searchTerm, currentPath, maxDepth - 1)
);
} else if (Array.isArray(data)) {
searchFindings = searchFindings.concat(
whereArray(data, searchTerm, currentPath, maxDepth - 1)
);
} else {
// console.log("@", currentPath, "=>", data);
if (data === searchTerm) {
searchFindings.push(currentPath);
}
}
});
return searchFindings;
};
/**
* @param {unknown[]} arr
* @param {string|number} searchTerm
* @param {string} currPath
* @return string[]
**/
const whereArray = (arr, searchTerm, currPath = "", maxDepth = 8) => {
if (maxDepth < 0) return [];
/** @type string[] */
let searchFindings = [];
arr.forEach((data, index) => {
const currentPath = `${currPath}[${index}]`;
if (isObject(data)) {
searchFindings = searchFindings.concat(
whereTheHeckIs(data, searchTerm, currentPath, maxDepth - 1)
);
} else if (Array.isArray(data)) {
searchFindings = searchFindings.concat(
whereArray(data, searchTerm, currentPath, maxDepth - 1)
);
} else {
// console.log("@", currentPath, "=>", data);
if (data === searchTerm) {
searchFindings.push(currentPath);
}
}
});
return searchFindings;
};
window.whereTheHeckIs = whereTheHeckIs;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment