Skip to content

Instantly share code, notes, and snippets.

@fed135
Last active September 4, 2018 11:57
Show Gist options
  • Save fed135/74498feebf494bb6ef0def1cc578a2cd to your computer and use it in GitHub Desktop.
Save fed135/74498feebf494bb6ef0def1cc578a2cd to your computer and use it in GitHub Desktop.
Table builder (Time limit 2h30)
function printTable(table) {
const options = {
padding: 1,
columns: table.reduce(parseColumns, []),
lineSize: 1,
};
options.lineSize = options.columns.reduce((num, col) => {
return num + col.size + (options.padding * 2) + 1;
}, 1);
function parseColumns(cols, row) {
for (let key in row) {
const len = parseEntry(row[key]).length;
let present = false;
for (let i = 0; i < cols.length; i++) {
if (cols[i].key === key) {
present = true;
if (cols[i].size < len) cols[i].size = len;
continue;
}
}
if (!present) cols.push({ key, size: Math.max(len, key.length) });
}
return cols;
}
function line() {
return '-'.repeat(options.lineSize);
}
function pre() {
return ' '.repeat(options.padding);
}
function post(value, column) {
return ' '.repeat(Math.max(0, column.size - value.length) + options.padding);
}
function header() {
return `|${options.columns.map(col => cell(col.key, col)).join('|')}|`;
}
function parseEntry(value) {
if (value === undefined) value = '';
if (typeof value !== 'string') value = JSON.stringify(value);
return value;
}
function cell(value, column) {
return `${pre()}${value}${post(value, column)}`;
}
function row(cells, index) {
return `|${options.columns.map((col) => {
return cell(parseEntry(cells[col.key]), col);
}).join('|')}|`;
}
return [
line(), '\n',
header(), '\n',
line(), '\n',
table.map(row).join('\n'), '\n',
line(), '\n'
].join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment