Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Created November 23, 2022 12:34
Show Gist options
  • Save jbreckmckye/78bbe96fee9bde6b5a3722837588e168 to your computer and use it in GitHub Desktop.
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
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