Skip to content

Instantly share code, notes, and snippets.

@eneuhauser
Last active March 31, 2017 20:06
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 eneuhauser/47780d8b6bd5730e69d46f7e3aca6bd4 to your computer and use it in GitHub Desktop.
Save eneuhauser/47780d8b6bd5730e69d46f7e3aca6bd4 to your computer and use it in GitHub Desktop.
Output a table of array of arrays in the console.
function toTable(data, headings=[], cellspacing=2, cellpadding=1) {
const widths = data.concat([headings]).reduce((widths, r) => r.reduce((ws, c, i) => {
let cur = ws[i] || 0, w = String(c).length;
ws[i] = w > cur ? w : cur;
return ws;
}, widths), []).map(w => w + cellpadding * 2), cs = center('|', cellspacing + 1);
if(headings.length) {
console.log(headings.map((h, i) => pad(center(h, widths[i]))).join(cs));
console.log(widths.map(w => '-'.repeat(w+cellpadding*2)).join(cs));
}
data.forEach(r => console.log(r.map((c, i) => pad(align(c, widths[i]))).join(cs)));
function align(val, w) {
const p = ' '.repeat(w - String(val).length);
return typeof val === 'number' ? p + val : val + p;
}
function center(val, w) {
const half = (w - String(val).length) / 2;
return ' '.repeat(Math.ceil(half)) + val + ' '.repeat(Math.floor(half));
}
function pad(cell) {
const padding = ' '.repeat(cellpadding);
return padding+cell+padding;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment