-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathmarkdown-table-generator.service.ts
More file actions
65 lines (54 loc) · 1.75 KB
/
Copy pathmarkdown-table-generator.service.ts
File metadata and controls
65 lines (54 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
export type MarkdownTableAlignment = 'left' | 'center' | 'right';
export interface MarkdownTable {
headers: string[]
alignments: MarkdownTableAlignment[]
rows: string[][]
}
const alignmentSeparators: Record<MarkdownTableAlignment, string> = {
left: ':---',
center: ':---:',
right: '---:',
};
export function createMarkdownTable({ rows = 2, columns = 3 }: { rows?: number; columns?: number } = {}): MarkdownTable {
return {
headers: Array.from({ length: columns }, (_, index) => `Column ${index + 1}`),
alignments: Array.from({ length: columns }, () => 'left'),
rows: Array.from({ length: rows }, () => Array.from({ length: columns }, () => '')),
};
}
export function escapeMarkdownTableCell(value: string): string {
return value
.replace(/\|/g, '\\|')
.replace(/\r\n|\r|\n/g, '<br>')
.trim();
}
function getColumnCount(table: MarkdownTable): number {
return Math.max(
table.headers.length,
table.alignments.length,
...table.rows.map(row => row.length),
);
}
function getCells(cells: string[], columns: number): string[] {
return Array.from({ length: columns }, (_, index) => escapeMarkdownTableCell(cells[index] ?? ''));
}
function formatRow(cells: string[]): string {
return `| ${cells.join(' | ')} |`;
}
export function generateMarkdownTable(table: MarkdownTable): string {
const columns = getColumnCount(table);
if (columns === 0) {
return '';
}
const headers = getCells(table.headers, columns);
const separators = Array.from(
{ length: columns },
(_, index) => alignmentSeparators[table.alignments[index] ?? 'left'],
);
const rows = table.rows.map(row => formatRow(getCells(row, columns)));
return [
formatRow(headers),
formatRow(separators),
...rows,
].join('\n');
}