Skip to content

Instantly share code, notes, and snippets.

@guillaumegarcia13
Created October 16, 2020 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumegarcia13/9f1025a0b6655910e61cb796bdc23b38 to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/9f1025a0b6655910e61cb796bdc23b38 to your computer and use it in GitHub Desktop.
Inspect object and return getter methods in console.table
var inspect = function(ctrl, prototypeLevel = 1) {
let output = [];
let level = prototypeLevel;
// local auxiliary helper
const _fillDictionary = (subObj, depth, originalObj = subObj) => {
Object.keys(subObj).forEach(key => {
// only consider 'getter' and catch any error (such as mandatory parameters)
if (key.startsWith('get') && typeof originalObj[key] === 'function') {
try {
output.push({ depth: depth, key: key, value: originalObj[key]() });
} catch(error) {
console.error(key, originalObj[key]);
}
}
});
};
// Object itself
ctrl && _fillDictionary(ctrl, 0);
// And its chain of prototype
let parent = ctrl;
while (level > 0 && parent) {
let proto = (Object.getPrototypeOf && Object.getPrototypeOf(parent)) ||
parent.__proto__;
let depth = prototypeLevel - level + 1;
proto && _fillDictionary(proto, depth, ctrl);
// update loop
level--;
parent = proto;
}
// Sorting
// output.sort((a, b) => a.key.localeCompare(b.key));
output.sort((a, b) => a.depth - b.depth || // sort by depth
a.key.localeCompare(b.key)); // then by key
(console.table) ? console.table(output)
: console.log(output);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment