(
rows_: (string | number)[][],
opts: TextTableOptions = {},
)
| 38 | }; |
| 39 | |
| 40 | export function textTable( |
| 41 | rows_: (string | number)[][], |
| 42 | opts: TextTableOptions = {}, |
| 43 | ): string { |
| 44 | const hsep = ' '; |
| 45 | const align = opts.align ?? []; |
| 46 | const stringLength = opts.stringLength ?? ((str: string) => str.length); |
| 47 | |
| 48 | const sizes = rows_.reduce((acc: number[], row: (string | number)[]) => { |
| 49 | row.forEach((c: string | number, ix: number) => { |
| 50 | const n = stringLength(String(c)); |
| 51 | |
| 52 | if (!acc[ix] || n > acc[ix]) { |
| 53 | // eslint-disable-next-line functional/immutable-data,no-param-reassign |
| 54 | acc[ix] = n; |
| 55 | } |
| 56 | }); |
| 57 | return acc; |
| 58 | }, []); |
| 59 | |
| 60 | return rows_ |
| 61 | .map((row: (string | number)[]) => |
| 62 | row |
| 63 | .map((c: string | number, ix: number) => { |
| 64 | const cellStr = String(c); |
| 65 | const n = (sizes[ix] ?? 0) - stringLength(cellStr) || 0; |
| 66 | const s = Array.from({ length: Math.max(n + 1, 1) }).join(' '); |
| 67 | |
| 68 | if (align[ix] === 'r') { |
| 69 | return s + cellStr; |
| 70 | } |
| 71 | |
| 72 | return cellStr + s; |
| 73 | }) |
| 74 | .join(hsep) |
| 75 | .trimEnd(), |
| 76 | ) |
| 77 | .join('\n'); |
| 78 | } |
no test coverage detected