Last active
March 31, 2017 20:06
-
-
Save eneuhauser/47780d8b6bd5730e69d46f7e3aca6bd4 to your computer and use it in GitHub Desktop.
Output a table of array of arrays in the console.
This file contains 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 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