Created
November 23, 2022 12:34
-
-
Save jbreckmckye/78bbe96fee9bde6b5a3722837588e168 to your computer and use it in GitHub Desktop.
TypeScript functions for printing a matrix of data as either CSV or a markdown table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Stringable = string | { toString(): string } | |
export function toCSV <T extends Stringable>(items: T[][]): string { | |
return items.map(row => row.join(',')).join('\n') | |
} | |
export function markdownTable (items: Stringable[][]): string { | |
const asStrings = items.map( | |
row => row.map(item => typeof item === 'string' ? item : item.toString()) | |
) | |
const colSizes = asStrings.reduce<number[]>( | |
(acc, line) => { | |
const lineCols = line.map(col => col.length) | |
return lineCols.map( | |
(lineCol, index) => Math.max(lineCol, acc[index] || 0) | |
) | |
}, | |
[] | |
) | |
const padded = asStrings.map(line => | |
line.map((col, colIndex) => { | |
return ` ${col.padEnd(colSizes[colIndex], ' ')} ` | |
}) | |
) | |
const asLines = padded.map( | |
line => line.join('|') | |
) | |
const lineLen = asLines[0].length | |
asLines.splice(1, 0, '-'.repeat(lineLen)) | |
const asTable = asLines.map( | |
line => `|${line}|` | |
) | |
return asTable.join('\n') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment