Skip to content

Commit

Permalink
feat: add a flatten combinator, that will flatten a slice of strings …
Browse files Browse the repository at this point in the history
…into a single string (#65)
  • Loading branch information
purpleclay authored Oct 13, 2024
1 parent bba4768 commit 12c9d0e
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
14 changes: 14 additions & 0 deletions docs/combinators.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,20 @@ chomp.Opt(chomp.Tag("Hey"))("Hello, World!")
rem: "Hello, World!"
ext: ""
....

|https://pkg.go.dev/github.com/purpleclay/chomp#Flatten[Flatten]
|
[source,go]
----
chomp.Flatten(
chomp.Many(chomp.Parentheses()),
)("(H)(el)(lo), World!")
----
|
....
rem: ", World!"
ext: "Hello"
....
|===

== Ready-made parsers [[ready-made_parsers]]
Expand Down
22 changes: 21 additions & 1 deletion modifier.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package chomp

import "fmt"
import (
"fmt"
"strings"
)

// MappedCombinator is a function capable of converting the output from a [Combinator]
// into any given type. Upon success, it will return the unparsed text, along with the
Expand Down Expand Up @@ -101,3 +104,20 @@ func Peek[T Result](c Combinator[T]) Combinator[T] {
return s, ext, err
}
}

// Flatten the output of a [Combinator] by joining all extracted values
// into a string.
//
// chomp.Flatten(
// chomp.Many(chomp.Parentheses()),
// )("(H)(el)(lo), World!")
// // (", World!", "Hello", nil)
func Flatten(c Combinator[[]string]) Combinator[string] {
return func(s string) (string, string, error) {
rem, ext, err := c(s)
if err != nil {
return rem, "", ParserError{Err: err, Type: "flatten"}
}
return rem, strings.Join(ext, ""), nil
}
}
12 changes: 12 additions & 0 deletions modifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,15 @@ func TestPeekUsingSequence(t *testing.T) {
assert.Equal(t, "Hello and Good Morning!", rem)
assert.Equal(t, []string{"Hello", "and", "Good"}, ext)
}

func TestFlatten(t *testing.T) {
t.Parallel()

rem, ext, err := chomp.Flatten(
chomp.Many(chomp.Parentheses()),
)("(H)(el)(lo) and Good Morning!")

require.NoError(t, err)
assert.Equal(t, " and Good Morning!", rem)
assert.Equal(t, "Hello", ext)
}

0 comments on commit 12c9d0e

Please sign in to comment.