Skip to content

Instantly share code, notes, and snippets.

@MoritzKn
Last active Dec 18, 2020
Embed
What would you like to do?
Print aligned tables
function alignedTable({
alignments = [],
separator = ' ',
prefix = '',
suffix = '',
newLine = '\n',
rows = [],
} = {}) {
function toString() {
const lengths = {};
const onlyNumbers = {};
let table = '';
rows.forEach((row, rowIndex) => {
row.forEach((cell, cellIndex) => {
cell = String(cell);
lengths[cellIndex] = Math.max(lengths[cellIndex] || 0, cell.length);
onlyNumbers[cellIndex] =
(onlyNumbers[cellIndex] === undefined || onlyNumbers[cellIndex]) &&
/^[0-9., ]*(\s*\w+)?$/.test(cell);
});
});
rows.forEach((row, rowIndex) => {
let line = prefix;
row.forEach((cell, cellIndex) => {
cell = String(cell);
if (cellIndex !== 0) {
line += separator;
}
const alignment =
alignments[cellIndex] || (onlyNumbers[cellIndex] ? 'r' : 'l');
if (alignment === 'r') {
line += cell.padStart(lengths[cellIndex]);
} else if (alignment === 'c') {
line += cell
.padStart(lengths[cellIndex] / 2 - cell.length / 2)
.padEnd(lengths[cellIndex]);
} else {
line += cell.padEnd(lengths[cellIndex]);
}
line += suffix;
});
table += line + newLine;
});
return table;
}
return {
row(...row) {
rows.push(row);
},
print() {
console.log(toString());
},
toString,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment