Last active
August 16, 2024 15:45
-
-
Save broskees/1c778885b80445a23b8acd930fff685c to your computer and use it in GitHub Desktop.
log all the functions attached to an object
This file contains hidden or 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 logFunctions(item, path = '', seen = new WeakMap(), depth = 0) { | |
const MAX_DEPTH = 10; | |
if (depth > MAX_DEPTH) { | |
return item; | |
} | |
if (item === null || ( | |
typeof item !== "object" | |
&& typeof item !== "function" | |
)) { | |
return item; | |
} | |
if (seen.has(item)) { | |
console.log('Circular reference:', path); | |
return seen.get(item); | |
} | |
// Handle arrays | |
if (Array.isArray(item)) { | |
const newArray = item.map((v, i) => logFunctions( | |
v, | |
[path, i.toString()].filter(Boolean).join('.'), | |
seen, | |
depth + 1 | |
)); | |
seen.set(item, newArray); | |
return newArray; | |
} | |
// Handle objects / functions | |
let result = null; | |
if (typeof item === "function") { | |
console.log('Function name:', path); | |
result = function (...args) { | |
const returnValue = item(...args); | |
console.log('Function info:', { | |
name: path, | |
args: args, | |
return: returnValue | |
}); | |
console.trace() | |
return returnValue; | |
}; | |
Object.assign(result, item); | |
} else { | |
result = Object.create(Object.getPrototypeOf(item)); | |
} | |
for (const [key, value] of Object.entries(item)) { | |
result[key] = logFunctions( | |
value, | |
[path, key].filter(Boolean).join('.'), | |
seen, | |
depth + 1 | |
); | |
} | |
seen.set(item, result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment