-
-
Save poori/4004097 to your computer and use it in GitHub Desktop.
A pretty printer for Javascript objects that looks like Ruby's pp formatter. In use on Rhino, untested elsewhere.
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 pp(object, depth, embedded) { | |
typeof(depth) == "number" || (depth = 0) | |
typeof(embedded) == "boolean" || (embedded = false) | |
var newline = false | |
var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += " "}; return spaces } | |
var pretty = "" | |
if ( typeof(object) == "undefined" ) { pretty += "undefined" } | |
else if ( typeof(object) == "boolean" || | |
typeof(object) == "number" ) { pretty += object.toString() } | |
else if ( typeof(object) == "string" ) { pretty += "\"" + object + "\"" } | |
else if ( object == null) { pretty += "null" } | |
else if ( object instanceof(Array) ) { | |
if ( object.length > 0 ) { | |
if (embedded) { newline = true } | |
var content = "" | |
for (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) } | |
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"") | |
pretty += "[ " + content + "\n" + spacer(depth) + "]" | |
} else { pretty += "[]" } | |
} | |
else if (typeof(object) == "object") { | |
if ( Object.keys(object).length > 0 ){ | |
if (embedded) { newline = true } | |
var content = "" | |
for (var key in object) { | |
content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n" | |
} | |
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"") | |
pretty += "{ " + content + "\n" + spacer(depth) + "}" | |
} else { pretty += "{}"} | |
} | |
else { pretty += object.toString() } | |
return ((newline ? "\n" + spacer(depth) : "") + pretty) | |
} |
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
js> pp({foo:"bar", baz: 1}) | |
{ foo: "bar", | |
baz: 1 | |
} | |
js> var taco | |
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}}) | |
{ foo: "bar", | |
baz: | |
[ 1, | |
"taco", | |
{ blarg: "moo", | |
mine: "craft" | |
}, | |
null, | |
undefined, | |
{} | |
], | |
bleep: | |
{ a: null, | |
b: undefined, | |
c: [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
edited line 16: from 'for each' to 'for' since it was causing syntax errors in chrome...