From 8b4e9a9e2203a375b36a3fa5139e686f43a1326c Mon Sep 17 00:00:00 2001 From: bjt-user Date: Tue, 30 Apr 2024 23:52:13 +0200 Subject: [PATCH] seems to work, but might need unit tests --- main.go | 47 +++++++++++++++++++++++++++++------------- tests/weird_headers.md | 33 +++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 tests/weird_headers.md diff --git a/main.go b/main.go index 1203ca6..f5ac434 100644 --- a/main.go +++ b/main.go @@ -10,9 +10,10 @@ import ( ) type heading struct { - text string - level int - line int + text string + level int + line int + parent *heading } func is_heading(line string) bool { @@ -31,29 +32,45 @@ func get_heading_level(heading_text string) int { return level } -func count_levels(headings []heading) map[int]int { - level_count := make(map[int]int) +func count_levels(headings []heading) [6]int { + level_count := [6]int{} for index, _ := range headings { switch headings[index].level { case 1: - level_count[1]++ + level_count[0]++ case 2: - level_count[2]++ + level_count[1]++ case 3: - level_count[3]++ + level_count[2]++ case 4: - level_count[4]++ + level_count[3]++ case 5: - level_count[5]++ + level_count[4]++ case 6: - level_count[6]++ + level_count[5]++ } } return level_count } +func get_parents(headings []heading) { + for index, _ := range headings { + if index == 0 { + headings[index].parent = nil + continue + } + + for i := (index - 1); i >= 0; i-- { + if headings[i].level < headings[index].level { + headings[index].parent = &headings[i] + break + } + } + } +} + func main() { file_content_raw, err := os.ReadFile(os.Args[1]) @@ -70,17 +87,19 @@ func main() { for index, value := range file_lines { if is_heading(value) { headings = append( - headings, heading{value, get_heading_level(value), (index + 1)}) + headings, heading{value, get_heading_level(value), (index + 1), nil}) } } + get_parents(headings) + fmt.Printf("%v\n", headings) header_level_count := count_levels(headings) - for i := 0; i <= 6; i++ { + for i := 0; i < 6; i++ { if header_level_count[i] != 0 { - fmt.Printf("Header %d occurs %d times.\n", i, header_level_count[i]) + fmt.Printf("Header %d occurs %d times.\n", (i + 1), header_level_count[i]) } } } diff --git a/tests/weird_headers.md b/tests/weird_headers.md new file mode 100644 index 0000000..0dbc917 --- /dev/null +++ b/tests/weird_headers.md @@ -0,0 +1,33 @@ +some text. + +#### test markdown doc + +## header2 + +#### header4 + +some text. + +```bash +echo 'hi' +``` + +#### another header4 + +more text. + +####third header4 + +####fourth #header4 + + ## this is not a header anymore + +##### header5 + +## a second header2 + +#### testing + +``` +cool code +```