Skip to content

Commit

Permalink
lib: refactor to use primordials in lib/internal/cli_table
Browse files Browse the repository at this point in the history
PR-URL: #38046
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
  • Loading branch information
marsonya authored and Trott committed Apr 6, 2021
1 parent 66c8f76 commit a9332e8
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions lib/internal/cli_table.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
'use strict';

const {
ArrayPrototypeJoin,
ArrayPrototypeMap,
MathCeil,
MathMax,
MathMaxApply,
ObjectPrototypeHasOwnProperty,
StringPrototypeRepeat,
} = primordials;

const { getStringWidth } = require('internal/util/inspect');
Expand Down Expand Up @@ -39,7 +43,8 @@ const renderRow = (row, columnWidths) => {
const needed = (columnWidths[i] - len) / 2;
// round(needed) + ceil(needed) will always add up to the amount
// of spaces we need while also left justifying the output.
out += `${' '.repeat(needed)}${cell}${' '.repeat(MathCeil(needed))}`;
out += StringPrototypeRepeat(' ', needed) + cell +
StringPrototypeRepeat(' ', MathCeil(needed));
if (i !== row.length - 1)
out += tableChars.middle;
}
Expand All @@ -49,8 +54,9 @@ const renderRow = (row, columnWidths) => {

const table = (head, columns) => {
const rows = [];
const columnWidths = head.map((h) => getStringWidth(h));
const longestColumn = columns.reduce((n, a) => MathMax(n, a.length), 0);
const columnWidths = ArrayPrototypeMap(head, (h) => getStringWidth(h));
const longestColumn = MathMaxApply(ArrayPrototypeMap(columns, (a) =>
a.length));

for (let i = 0; i < head.length; i++) {
const column = columns[i];
Expand All @@ -65,18 +71,22 @@ const table = (head, columns) => {
}
}

const divider = columnWidths.map((i) =>
tableChars.middleMiddle.repeat(i + 2));
const divider = ArrayPrototypeMap(columnWidths, (i) =>
StringPrototypeRepeat(tableChars.middleMiddle, i + 2));

let result = `${tableChars.topLeft}${divider.join(tableChars.topMiddle)}` +
`${tableChars.topRight}\n${renderRow(head, columnWidths)}\n` +
`${tableChars.leftMiddle}${divider.join(tableChars.rowMiddle)}` +
`${tableChars.rightMiddle}\n`;
let result = tableChars.topLeft +
ArrayPrototypeJoin(divider, tableChars.topMiddle) +
tableChars.topRight + '\n' +
renderRow(head, columnWidths) + '\n' +
tableChars.leftMiddle +
ArrayPrototypeJoin(divider, tableChars.rowMiddle) +
tableChars.rightMiddle + '\n';

for (const row of rows)
result += `${renderRow(row, columnWidths)}\n`;

result += `${tableChars.bottomLeft}${divider.join(tableChars.bottomMiddle)}` +
result += tableChars.bottomLeft +
ArrayPrototypeJoin(divider, tableChars.bottomMiddle) +
tableChars.bottomRight;

return result;
Expand Down

0 comments on commit a9332e8

Please sign in to comment.