Created
October 16, 2020 09:58
-
-
Save guillaumegarcia13/9f1025a0b6655910e61cb796bdc23b38 to your computer and use it in GitHub Desktop.
Inspect object and return getter methods in console.table
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
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