Skip to content

Commit

Permalink
feat: add ZipWithIndex
Browse files Browse the repository at this point in the history
  • Loading branch information
Primetalk committed Oct 16, 2022
1 parent 305657f commit 8f894eb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
19 changes: 19 additions & 0 deletions stream/zip.go
@@ -0,0 +1,19 @@
package stream

import (
"github.com/primetalk/goio/fun"
"github.com/primetalk/goio/io"
)

// ZipWithIndex prepends the index to each element.
func ZipWithIndex[A any](as Stream[A]) Stream[fun.Pair[int, A]] {
return StateFlatMap(as, 0,
func(a A, i int) io.IO[fun.Pair[int, Stream[fun.Pair[int, A]]]] {
return io.Lift(
fun.NewPair(i+1, Lift(
fun.NewPair(i, a),
)),
)
},
)
}
15 changes: 15 additions & 0 deletions stream/zip_test.go
@@ -0,0 +1,15 @@
package stream_test

import (
"testing"

"github.com/primetalk/goio/slice"
"github.com/primetalk/goio/stream"
"github.com/stretchr/testify/assert"
)

func TestZipWithIndex(t *testing.T) {
natsWithIndex := UnsafeStreamToSlice(t, stream.ZipWithIndex(nats10))
sNatsWithIndex := slice.ZipWithIndex(slice.Nats(10))
assert.ElementsMatch(t, sNatsWithIndex, natsWithIndex)
}

0 comments on commit 8f894eb

Please sign in to comment.