From abd4c60339c1224a2a330d3b1cd2b003fbb1ed2a Mon Sep 17 00:00:00 2001 From: bjt-user Date: Tue, 30 Apr 2024 10:50:58 +0200 Subject: [PATCH] used struct to represent the headers --- main.go | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 62edd39..e099348 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,12 @@ import ( "strings" ) +type heading struct { + text string + level int + line int +} + func is_heading(line string) bool { if strings.HasPrefix(line, "#") { return true @@ -21,20 +27,22 @@ func is_heading(line string) bool { } } -func get_heading_level(heading string) int { +func get_heading_level(heading_text string) int { level := 0 - for i := 0; heading[i] == '#'; i++ { + for i := 0; heading_text[i] == '#'; i++ { level += 1 } return level } -func print_toc(headings []string) { +func print_toc(headings []heading) { tab_count := 0 - for index, value := range headings { + for index, _ := range headings { if index > 0 { - prev_level := get_heading_level(headings[index-1]) - cur_level := get_heading_level(headings[index]) + prev_level := get_heading_level(headings[index-1].text) + cur_level := get_heading_level(headings[index].text) + + headings[index].level = cur_level if cur_level > prev_level { tab_count += (cur_level - prev_level) @@ -45,14 +53,14 @@ func print_toc(headings []string) { fmt.Printf("\t") } } - fmt.Printf("%s\n", value) + fmt.Printf("%v\n", headings[index]) } } func main() { file_content_raw, err := os.ReadFile(os.Args[1]) - var headings []string = nil + var headings []heading = nil if err != nil { log.Fatal(err) @@ -64,7 +72,7 @@ func main() { for _, value := range file_lines { if is_heading(value) { - headings = append(headings, value) + headings = append(headings, heading{value, 0, 0}) } }