Skip to content

Instantly share code, notes, and snippets.

@szkrd
Created September 17, 2020 10:05
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 szkrd/5572c4d2c4fa3de2351a6c5b472621c0 to your computer and use it in GitHub Desktop.
Save szkrd/5572c4d2c4fa3de2351a6c5b472621c0 to your computer and use it in GitHub Desktop.
Make json snapshots less painful: replace functions/classes with their names (if possible), convert dates to numbers, remove undefined enumerable properties
function logObject(obj) {
let result = JSON.stringify(obj, null, 2);
let hr = '';
for (let i = 0; i < 80; i++) { hr += '-'; }
const lines = result.split('\n');
result = lines.map(line => line.replace(/^(\s+)"([a-zA-Z0-9_$]*)"/, '$1$2')).join('\n');
console.log(`${hr}{{{\n${result}\n}}}${hr}`);
}
function stringifyComplexObjects(obj) {
JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value && Object.keys(value).length > 0) {
Object.keys(value).forEach((iterKey) => {
const iterVal = value[iterKey];
if (typeof iterVal === 'function') {
// this is kinda fuzzy, decorators may mess this up, so don't expect wonders
const subType = iterVal && iterVal.prototype && iterVal.prototype.constructor && /^\s*class/.test(iterVal.toString()) ? 'class' : 'function';
value[iterKey] = subType + (iterVal.name ? `:${iterVal.name}` : '');
} else if (iterVal instanceof Date) {
value[iterKey] = iterVal.getTime();
} else if (iterVal === undefined) {
delete value[iterKey];
}
});
}
return value;
});
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment