feat: generate 1 line for markdown

main
hau 2020-11-27 18:02:33 +07:00 committed by Nguyen Tran Hau
parent b09a0eae9a
commit 848b362683
5 changed files with 80 additions and 8 deletions

View File

@ -15,7 +15,7 @@ const (
// Base is single markdown syntax representation
// Example: header, list, ...
type Base interface {
ToString() string
String() string
}
type header struct {
@ -23,7 +23,14 @@ type header struct {
text string
}
func (h header) ToString() string {
func NewHeader(level int, text string) Base {
return header{
level: level,
text: text,
}
}
func (h header) String() string {
var builder strings.Builder
for i := 0; i < h.level; i++ {
@ -42,7 +49,13 @@ type listItem struct {
text string
}
func (i listItem) ToString() string {
func NewListItem(text string) Base {
return listItem{
text: text,
}
}
func (i listItem) String() string {
text := strings.TrimSpace(i.text)
return string(defaultListToken) + string(spaceToken) + text

View File

@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
)
func TestHeaderToString(t *testing.T) {
func TestHeaderString(t *testing.T) {
tests := []struct {
name string
header header
@ -32,13 +32,13 @@ func TestHeaderToString(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := tc.header.ToString()
got := tc.header.String()
assert.Equal(t, tc.want, got)
})
}
}
func TestListItemToString(t *testing.T) {
func TestListItemString(t *testing.T) {
tests := []struct {
name string
listItem listItem
@ -55,7 +55,7 @@ func TestListItemToString(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := tc.listItem.ToString()
got := tc.listItem.String()
assert.Equal(t, tc.want, got)
})
}

13
pkg/markdown/generate.go Normal file
View File

@ -0,0 +1,13 @@
package markdown
import "strings"
func Generate(bases []Base) string {
lines := make([]string, len(bases))
for i, base := range bases {
lines[i] = base.String()
}
return strings.Join(lines, string(newlineToken))
}

View File

@ -0,0 +1,39 @@
package markdown
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGenerate(t *testing.T) {
tests := []struct {
name string
bases []Base
want string
}{
{
name: "normal",
bases: []Base{
header{
level: 1,
text: "header",
},
listItem{
text: "item 1",
},
listItem{
text: "item 2",
},
},
want: "# header\n- item 1\n- item 2",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := Generate(tc.bases)
assert.Equal(t, tc.want, got)
})
}
}

View File

@ -36,7 +36,7 @@ func TestParse(t *testing.T) {
},
want: []Base{
header{
level: 1,
level: 3,
text: "xyz",
},
listItem{
@ -45,6 +45,13 @@ func TestParse(t *testing.T) {
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := Parse(tc.lines)
assert.Equal(t, tc.want, got)
})
}
}
func TestParseHeader(t *testing.T) {