Skip to content

Instantly share code, notes, and snippets.

@AverageMarcus
Created March 28, 2013 20:39
Show Gist options
  • Save AverageMarcus/5266600 to your computer and use it in GitHub Desktop.
Save AverageMarcus/5266600 to your computer and use it in GitHub Desktop.
Implementing a console.table() like feature to help with debugging
function console_table(xs) {
function pad(n, s) {
var res = s;
for (var i = s.length; i < n; i++)
res += " ";
return res;
}
if (xs.length === 0)
console.log("No data");
else {
var widths = [];
var cells = [];
for (var i = 0; i <= xs.length; i++)
cells.push([]);
for (var s in xs[0]) {
var len = s.length;
cells[0].push(s);
for (var i = 0; i < xs.length; i++) {
var ss = "" + xs[i][s];
len = Math.max(len, ss.length);
cells[i + 1].push(ss);
}
widths.push(len);
}
var s = "";
for (var x = 0; x < cells.length; x++) {
for (var y = 0; y < widths.length; y++)
s += "|" + pad(widths[y], cells[x][y]);
s += "|\n";
}
console.log(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment