Skip to content

Commit

Permalink
Add UnzipFirst and UnzipSecond stream functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
jpfourny committed Mar 1, 2024
1 parent dbb0107 commit c5a5e65
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
34 changes: 34 additions & 0 deletions pkg/stream/combine.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,37 @@ func Zip[E, F any](s1 Stream[E], s2 Stream[F]) Stream[pair.Pair[E, F]] {
func ZipWithIndex[E any, I constraint.Integer](s Stream[E], offset I) Stream[pair.Pair[E, I]] {
return Zip(s, Walk(offset, pred.True[I](), mapper.Increment[I](1)))
}

// UnzipFirst returns a stream that contains the first elements of each pair in the input stream.
//
// Example usage:
//
// s := stream.UnzipFirst(
// stream.Of(
// pair.Of(1, "foo"),
// pair.Of(2, "bar"),
// ),
// )
// out := stream.DebugString(s) // "<1, 2>"
func UnzipFirst[E, F any](s Stream[pair.Pair[E, F]]) Stream[E] {
return Map(s, func(p pair.Pair[E, F]) E {
return p.First()
})
}

// UnzipSecond returns a stream that contains the second elements of each pair in the input stream.
//
// Example usage:
//
// s := stream.UnzipSecond(
// stream.Of(
// pair.Of(1, "foo"),
// pair.Of(2, "bar"),
// ),
// )
// out := stream.DebugString(s) // "<foo, bar>"
func UnzipSecond[E, F any](s Stream[pair.Pair[E, F]]) Stream[F] {
return Map(s, func(p pair.Pair[E, F]) F {
return p.Second()
})
}
38 changes: 38 additions & 0 deletions pkg/stream/combine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,41 @@ func TestZipWithIndex(t *testing.T) {
assert.ElementsMatch(t, got, want)
})
}

func TestUnzipFirst(t *testing.T) {
t.Run("empty", func(t *testing.T) {
s := UnzipFirst(Empty[pair.Pair[int, string]]())
got := CollectSlice(s)
var want []int
assert.ElementsMatch(t, got, want)
})

t.Run("non-empty", func(t *testing.T) {
s := UnzipFirst(Of(
pair.Of(1, "foo"),
pair.Of(2, "bar"),
))
got := CollectSlice(s)
want := []int{1, 2}
assert.ElementsMatch(t, got, want)
})
}

func TestUnzipSecond(t *testing.T) {
t.Run("empty", func(t *testing.T) {
s := UnzipSecond(Empty[pair.Pair[int, string]]())
got := CollectSlice(s)
var want []string
assert.ElementsMatch(t, got, want)
})

t.Run("non-empty", func(t *testing.T) {
s := UnzipSecond(Of(
pair.Of(1, "foo"),
pair.Of(2, "bar"),
))
got := CollectSlice(s)
want := []string{"foo", "bar"}
assert.ElementsMatch(t, got, want)
})
}

0 comments on commit c5a5e65

Please sign in to comment.