Skip to content

Commit

Permalink
Add String and ToString
Browse files Browse the repository at this point in the history
  • Loading branch information
Soft committed Feb 24, 2022
1 parent 18ab84a commit f2da05c
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,23 @@ func Slice[T any](slice []T) Iterator[T]
`Slice` returns an Iterator that yields elements from a slice.

```go
func Func[T any](fn func() Option[T]) Iterator[T]
func String(input string) Iterator[rune]
```

`Func` returns an Iterator from a function.
`String` returns an Iterator yielding runes from the supplied string.

```go
func Range(start, stop, step int) Iterator[int]
```

`Range` returns an Iterator over a range of integers.

```go
func Func[T any](fn func() Option[T]) Iterator[T]
```

`Func` returns an Iterator from a function.

```go
func Once[T any](value T) Iterator[T]
```
Expand Down Expand Up @@ -145,6 +151,12 @@ func ToSlice[T any](it Iterator[T]) []T

`ToSlice` consumes an Iterator creating a slice from the yielded values.

```go
func ToString(it Iterator[rune]) string
```

`ToString` consumes a rune Iterator creating a string.

```go
func Find[T any](it Iterator[T], pred func(T) bool) Option[T]
```
Expand Down
27 changes: 27 additions & 0 deletions iterator.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
package iter

import "unicode/utf8"

// Iterator[T] represents an iterator yielding elements of type T.
type Iterator[T any] interface {
// Next yields a new value from the Iterator.
Next() Option[T]
}

type stringIter struct {
input string
}

// String returns an Iterator yielding runes from the supplied string.
func String(input string) Iterator[rune] {
return &stringIter{
input: input,
}
}

func (it *stringIter) Next() Option[rune] {
if len(it.input) == 0 {
return None[rune]()
}
value, width := utf8.DecodeRuneInString(it.input)
it.input = it.input[width:]
return Some(value)
}

type rangeIter struct {
start, stop, step, i int
}
Expand Down Expand Up @@ -64,6 +86,11 @@ func ToSlice[T any](it Iterator[T]) []T {
return result
}

// ToString consumes a rune Iterator creating a string.
func ToString(it Iterator[rune]) string {
return string(ToSlice(it))
}

type mapIter[T, R any] struct {
inner Iterator[T]
fn func(T) R
Expand Down
19 changes: 19 additions & 0 deletions iterator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,22 @@ func TestEqualBy(t *testing.T) {
false,
)
}

func TestString(t *testing.T) {
equals(
t,
Equal(
String("Hello"),
Slice([]rune{'H', 'e', 'l', 'l', 'o'}),
),
true,
)
}

func TestToString(t *testing.T) {
equals(
t,
ToString(String("Hello")),
"Hello",
)
}

0 comments on commit f2da05c

Please sign in to comment.