Skip to content

Commit

Permalink
feat: implemented csv
Browse files Browse the repository at this point in the history
  • Loading branch information
costinmrr committed Nov 11, 2024
1 parent 45479b4 commit 4484248
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 1 deletion.
15 changes: 14 additions & 1 deletion types/csv/csv.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
package csv

import (
"encoding/csv"
"strings"
)

// IsCSV returns true if the content is a CSV.
func IsCSV(content string) error {
// TODO: implement this function
if content == "" {
return ErrEmptyContent
}
reader := csv.NewReader(strings.NewReader(content))
_, err := reader.ReadAll()
if err != nil {
return err
}

return nil
}
77 changes: 77 additions & 0 deletions types/csv/csv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package csv

import "testing"

func TestIsCSV(t *testing.T) {
type args struct {
content string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "empty",
args: args{content: ""},
wantErr: true,
},
{
name: "simple string is csv",
args: args{content: "foo"},
wantErr: false,
},
{
name: "csv comma separated",
args: args{content: "foo,bar\nbaz,qux"},
wantErr: false,
},
{
name: "csv semicolon separated",
args: args{content: "foo;bar\nbaz;qux"},
wantErr: false,
},
{
name: "csv tab separated",
args: args{content: "foo\tbar\nbaz\tqux"},
wantErr: false,
},
{
name: "csv pipe separated",
args: args{content: "foo|bar\nbaz|qux"},
wantErr: false,
},
{
name: "csv with quotes",
args: args{content: "\"foo\",\"bar\"\n\"baz\",\"qux\""},
wantErr: false,
},
{
name: "csv with quotes and commas",
args: args{content: "\"foo,bar\",\"baz,qux\"\n\"foo,bar\",\"baz,qux\""},
wantErr: false,
},
{
name: "different number of columns per line",
args: args{content: "foo,bar\nbaz"},
wantErr: true,
},
{
name: "empty lines",
args: args{content: "foo,bar\n\nbaz,qux"},
wantErr: false,
},
{
name: "different separators per line",
args: args{content: "foo,bar\nbaz;qux"},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := IsCSV(tt.args.content); (err != nil) != tt.wantErr {
t.Errorf("IsCSV() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
7 changes: 7 additions & 0 deletions types/csv/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package csv

import "errors"

var (
ErrEmptyContent = errors.New("empty content")
)

0 comments on commit 4484248

Please sign in to comment.