-
Notifications
You must be signed in to change notification settings - Fork 7
/
markdown_table.go
55 lines (51 loc) · 1.06 KB
/
markdown_table.go
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
package main
import (
"bytes"
"fmt"
"strconv"
)
//generate basic markdown table from slice of string slices
func markdownTable(t *[][]string) string {
maxLengthMap := make(map[int]int)
//1st pass: populate maxLengthMap
for rowIndex, row := range *t {
for cellIndex, cell := range row {
length := len(cell)
if rowIndex == 0 {
length += 4
}
if length > maxLengthMap[cellIndex] {
maxLengthMap[cellIndex] = length
}
}
}
var b bytes.Buffer
for rowIndex, row := range *t {
for cellIndex, cell := range row {
if rowIndex == 0 {
cell = "**" + cell + "**"
}
if cellIndex == 0 {
b.WriteByte('|')
}
b.WriteString(fmt.Sprintf("%-"+strconv.Itoa(maxLengthMap[cellIndex])+"s", cell))
b.WriteByte('|')
}
b.WriteByte('\n')
if rowIndex == 0 {
for cellIndex := range row {
if cellIndex == 0 {
b.WriteByte('|')
}
b.WriteByte(':')
for i := 0; i < (maxLengthMap[cellIndex] - 1); i++ {
b.WriteByte('-')
}
b.WriteByte('|')
}
b.WriteByte('\n')
}
}
b.WriteByte('\n')
return b.String()
}