-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtable.go
More file actions
56 lines (46 loc) · 1.31 KB
/
table.go
File metadata and controls
56 lines (46 loc) · 1.31 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
package markdownTable
import "strings"
func CreateMarkdownTable(head []string, body [][]string) string {
separator := "|"
columnWidths := make([]int, len(head))
//Calculate maximum column width based on headers
for i, val := range head {
columnWidths[i] = len(val)
}
//Calculate maximum column widths based on body data
for _, row := range body {
for i, val := range row {
if i < len(head) && len(val) > columnWidths[i] {
columnWidths[i] = len(val)
}
}
}
var str strings.Builder
//Build header row
for i, val := range head {
str.WriteString(separator + " " + padString(val, columnWidths[i]) + " ")
}
str.WriteString(separator + "\n")
//Build separator row
for _, width := range columnWidths {
str.WriteString(separator + " " + strings.Repeat("-", width) + " ")
}
str.WriteString(separator + "\n")
//Build body rows
//Ensure we only loop through columns present in the header
for _, row := range body {
for i := 0; i < len(head); i++ {
val := ""
if i < len(row) {
val = row[i]
}
str.WriteString(separator + " " + padString(val, columnWidths[i]) + " ")
}
str.WriteString(separator + "\n")
}
return str.String()
}
// Helper function to pad a string to the required length
func padString(val string, length int) string {
return val + strings.Repeat(" ", length-len(val))
}