diff options
author | Nicolas Stucki <nicolas.stucki@gmail.com> | 2021-08-24 17:17:40 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-24 17:17:40 +0200 |
commit | c4561ac9691a01bd5ceced5b41ce6e511b7fde70 (patch) | |
tree | 94188b82b722d92e9da58d6059dd5be981de19b3 /ext | |
parent | 93d83a84dbe1f6ecf93b596f88bc85ba378fa986 (diff) |
feat(extensions/console): right align numeric columns in table (#11748)
Diffstat (limited to 'ext')
-rw-r--r-- | ext/console/02_console.js | 19 |
1 files changed, 15 insertions, 4 deletions
diff --git a/ext/console/02_console.js b/ext/console/02_console.js index 40ff2e25d..178b3955b 100644 --- a/ext/console/02_console.js +++ b/ext/console/02_console.js @@ -191,13 +191,17 @@ return width; } - function renderRow(row, columnWidths) { + function renderRow(row, columnWidths, columnRightAlign) { let out = tableChars.left; for (let i = 0; i < row.length; i++) { const cell = row[i]; const len = getStringWidth(cell); - const needed = columnWidths[i] - len; - out += `${cell}${StringPrototypeRepeat(" ", needed)}`; + const padding = StringPrototypeRepeat(" ", columnWidths[i] - len); + if (columnRightAlign?.[i]) { + out += `${padding}${cell}`; + } else { + out += `${cell}${padding}`; + } if (i !== row.length - 1) { out += tableChars.middle; } @@ -206,6 +210,11 @@ return out; } + function canRightAlign(value) { + const isNumber = !isNaN(value); + return isNumber; + } + function cliTable(head, columns) { const rows = []; const columnWidths = ArrayPrototypeMap(head, (h) => getStringWidth(h)); @@ -214,6 +223,7 @@ (n, a) => MathMax(n, a.length), 0, ); + const columnRightAlign = new Array(columnWidths.length).fill(true); for (let i = 0; i < head.length; i++) { const column = columns[i]; @@ -225,6 +235,7 @@ const width = columnWidths[i] || 0; const counted = getStringWidth(value); columnWidths[i] = MathMax(width, counted); + columnRightAlign[i] &= canRightAlign(value); } } @@ -244,7 +255,7 @@ `${tableChars.rightMiddle}\n`; for (const row of rows) { - result += `${renderRow(row, columnWidths)}\n`; + result += `${renderRow(row, columnWidths, columnRightAlign)}\n`; } result += |