PDA

View Full Version : echo for any types including associative arrays / objects


futnpav
12-01-2010, 08:18 AM
I wrote a funny class to flatten (print) nearly any types to strings, including objects. Free for use, evolving, comment, and I am completely irresponsible of consequence after adoption, good, bad, disastrous,:D.
how to use
new omniEcho().echo(anything you like)
Code:
function getSpace(n) {
var n = parseInt(n, 10);
var spaces = "";
if(!isNaN(n) && n > 0) {
for(i = 0; i < n; i++) {
spaces += " ";
}
}
return spaces;
}
//echo any types, including objects (flatten and echo)
function omniEcho() {
// this.o = o;
this.depth = 0;
this.echo = function(o) {
var tab = getSpace(3 * this.depth);
var str = "";
if(o === undefined) {
str += "\nUNDEFINED\n";
} else if(typeof o == "object") {
if(o === null) {
str += "\n" + tab + "NULL\n";
} else if(o && o.length){
// length is preferred as for-in loop does not work in the preferred way with DOM Elements
for(var idx = 0; idx < o.length; idx++) {
switch(typeof o[idx]) {
case "object":
// alert("obj");
this.depth++;
str += this.echo(o[idx]);
this.depth--;
break;
default:
str += "\n" + tab + idx + ">>" + o[idx];
}
}
// recap objects whose length is not defined.
} else {
for(var idx in o) {
switch(typeof o[idx]) {
case "object":
// alert("obj");
str += "\n" + tab + idx + ">>";
this.depth++;
str += this.echo(o[idx]);
this.depth--;
break;
default:
str += "\n" + tab + idx + ">>" + o[idx];
}
}
}
} else {
str += "\n" + o.toString() + "\n";
}
return str;
}
}