Skip to content

Instantly share code, notes, and snippets.

@drphrozen
Last active December 16, 2015 21:38
Show Gist options
  • Save drphrozen/5500831 to your computer and use it in GitHub Desktop.
Save drphrozen/5500831 to your computer and use it in GitHub Desktop.
This will dump an object, skip functions and objects starting with DOM or HTM
function dumpObject(root, indent){
if(indent == null) indent = " ";
function toType(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1];
}
var queue = [{ data: root, level: 0 }];
function add(data, level, prepend) {
queue.push({data: data, level: level, prepend: prepend});
}
function toString(obj, level) {
var type = typeof(obj);
switch(type) {
case 'undefined':
case 'function':
return 'function() {...}';
case 'object':
var objectType = toType(obj);
switch(objectType) {
case 'Null':
case 'Date':
case 'Boolean':
case 'Error':
case 'Math':
case 'Number':
case 'String':
return obj;
case 'Array':
var newLevel = level + 1;
obj.reverse().forEach(function(value, index) {
add(value, newLevel, index + ": ");
});
return '[...';
default:
var startsWith = objectType.substring(0, 3);
switch(startsWith) {
case 'DOM':
case 'HTM':
return objectType + ' {...}';
}
var newLevel = level + 1;
Object.keys(obj).reverse().forEach(function(key) {
add(obj[key], newLevel, key + ": ");
});
return '{...';
}
break;
case 'number':
case 'boolean':
case 'string':
return obj;
default:
console.log("Unhandled " + type + ": " + objectType);
break;
}
return;
}
var out = '';
while(queue.length > 0) {
var node = queue.pop();
var str = toString(node.data, node.level);
if(typeof(str) === 'undefined') continue;
if(node.prepend != null) str = node.prepend + str;
for (var i = 0; i < node.level; i++) {
str = indent + str
};
out += str + "\n";
}
return out;
}
function testStringify(obj) {
try {
dumpObject(obj);
} catch(e) {
console.log(e.stack);
debugger;
}
}
function testDownloadBlob(obj) {
var blob = new Blob([dumpObject(obj)], {type: 'text/plain'});
window.open(URL.createObjectURL(blob), '_blank', '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment