Started writing documentation and adding examples

This commit is contained in:
Leon Mika 2023-04-24 06:09:22 +00:00
parent 7adb09d4db
commit 405bf812ee
5 changed files with 40 additions and 0 deletions

4
csv.go
View file

@ -6,6 +6,10 @@ import (
"io"
)
// CSVColumn is a filter function that reads the source as a CSV file and extracts the cell
// values of the named column, excluding the header itself. If the column cannot be found,
// the filter will produce nothing. If the column index is beyond the number of columns
// for a particular row, it will be skipped.
func CSVColumn(name string) func(r io.Reader, w io.Writer) error {
return func(r io.Reader, w io.Writer) error {
cr := csv.NewReader(r)

View file

@ -29,3 +29,16 @@ func TestCSVColumn(t *testing.T) {
})
})
}
func ExampleCSVColumn() {
script.Slice([]string{
"letter,fruit,word",
"a,apple,alpha",
"b,banana,bravo",
"c,cherry,charlie",
}).Filter(scriptx.CSVColumn("fruit")).Stdout()
// Output:
// apple
// banana
// cherry
}

View file

@ -5,10 +5,16 @@ import (
"os"
)
// Runnable is a pipeline that can be executed by Run. The *script.Pipe type implements this interface
type Runnable interface {
// Stdout invokes the runnable task with the result written to stdout, if successful. It returns the number
// of bytes written out, or an error if the task was unsuccessful.
Stdout() (int, error)
}
// Run takes a number of pipes and executes them in order, until they all succeed or the first error is encountered.
// If a runnable task fails with an error, it will write the error to stderr and terminate the program with exit code 1.
// It's designed to be used within the "main()" function.
func Run(pipes ...Runnable) {
for _, pipe := range pipes {
if _, err := pipe.Stdout(); err != nil {

View file

@ -5,6 +5,9 @@ import (
"io"
)
// ToJSON is a filter function which converts each line from the source to a JSON structure.
// The result is a line-terminated list of JSON objects.
// The passed in function is to return a Go value that can be marshalled to JSON value.
func ToJSON(fn func(line string) any) func(r io.Reader, w io.Writer) error {
return func(r io.Reader, w io.Writer) error {
return eachLine(r, func(line string) (err error) {

View file

@ -43,3 +43,17 @@ func TestToJSON(t *testing.T) {
})
})
}
func ExampleToJSON() {
fruits := []string{"apple", "banana", "pineapple"}
script.Slice(fruits).Filter(scriptx.ToJSON(func(fruit string) any {
return map[string]any{
"fruit": fruit,
"length": len(fruit),
}
})).Stdout()
// Output:
// {"fruit":"apple","length":5}
// {"fruit":"banana","length":6}
// {"fruit":"pineapple","length":9}
}