// Package markdown handles markdown to html conversion.
package markdown
// implementation to refactor
// 1. use strings.Builder for html
// 2. use switch for char statements
// 3. setup for cycle
// 4. use strings.Count for header counter
import (
"strconv"
"strings"
)
// Render translates markdown to HTML.
func Render(markdown string) string {
markdown = strings.Replace(markdown, "__", "<strong>", 1)
markdown = strings.Replace(markdown, "__", "</strong>", 1)
markdown = strings.Replace(markdown, "_", "<em>", 1)
markdown = strings.Replace(markdown, "_", "</em>", 1)
var header int
var list bool
var html strings.Builder
for pos := 0; pos < len(markdown); pos++ {
switch char := markdown[pos]; char {
case '#':
header = strings.Count(markdown, "#")
pos += header
html.WriteString("<h")
html.WriteString(strconv.Itoa(header))
html.WriteString(">")
case '*':
if !list {
html.WriteString("<ul>")
}
html.WriteString("<li>")
list = true
pos += 1
case '\n':
if list {
html.WriteString("</li>")
}
if header > 0 {
html.WriteString("</h")
html.WriteString(strconv.Itoa(header))
html.WriteString(">")
header = 0
}
default:
if pos == 0 {
html.WriteString("<p>")
}
html.WriteByte(char)
}
}
if header > 0 {
html.WriteString("</h")
html.WriteString(strconv.Itoa(header))
html.WriteString(">")
}
if list {
html.WriteString("</li></ul>")
}
if !list && header == 0 {
html.WriteString("</p>")
}
return html.String()
}