Skip to content

Commit

Permalink
feat: add combinators to handle text that is prefixed or suffixed (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
purpleclay authored Feb 14, 2024
1 parent bec3e33 commit e7df717
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
43 changes: 43 additions & 0 deletions basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,46 @@ func I(c Combinator[[]string], i int) Combinator[string] {
return rem, ext[i], nil
}
}

// Prefixed will firstly scan the input text for a defined prefix and discard it.
// The remaining input text will be matched against the [Combinator] and returned
// if successful. Both combinators must match.
//
// chomp.Prefixed(
// chomp.Tag(`"`),
// chomp.Tag("Hello"))(`"Hello, World!"`)
// // (`, World!"`, "Hello", nil)
func Prefixed(pre, c Combinator[string]) Combinator[string] {
return func(s string) (string, string, error) {
rem, _, err := pre(s)
if err != nil {
return rem, "", err
}

return c(rem)
}
}

// Suffixed will firstly scan the input text and match it against the [Combinator].
// The remaining text will be scanned for a defined suffix and discarded. Both
// combinators must match.
//
// chomp.Suffixed(
// chomp.Tag(", "),
// chomp.Tag("Hello"))("Hello, World!")
// // ("World!", "Hello", nil)
func Suffixed(suf, c Combinator[string]) Combinator[string] {
return func(s string) (string, string, error) {
rem, ext, err := c(s)
if err != nil {
return rem, "", err
}

rem, _, err = suf(rem)
if err != nil {
return rem, "", err
}

return rem, ext, nil
}
}
20 changes: 20 additions & 0 deletions basic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,26 @@ func TestI(t *testing.T) {
assert.Equal(t, "and", ext)
}

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

rem, ext, err := chomp.Prefixed(chomp.Tag(`"`), chomp.Tag("Hello"))(`"Hello, World"`)

require.NoError(t, err)
assert.Equal(t, `, World"`, rem)
assert.Equal(t, "Hello", ext)
}

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

rem, ext, err := chomp.Suffixed(chomp.Tag(","), chomp.Tag("Hello"))("Hello, World")

require.NoError(t, err)
assert.Equal(t, " World", rem)
assert.Equal(t, "Hello", ext)
}

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

Expand Down

0 comments on commit e7df717

Please sign in to comment.