1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add RepeateFn function

This commit is contained in:
dudaodong
2022-04-15 16:32:55 +08:00
parent f66c0938e5
commit dfc6b868fb
2 changed files with 40 additions and 0 deletions

View File

@@ -53,6 +53,24 @@ func (c *Channel) Repeat(done <-chan any, values ...any) <-chan any {
return dataStream
}
// RepeatFn return a chan, excutes fn repeatly, and put the result into retruned chan
// until close the `done` channel
func (c *Channel) RepeatFn(done <-chan any, fn func() any) <-chan any {
dataStream := make(chan any)
go func() {
defer close(dataStream)
for {
select {
case <-done:
return
case dataStream <- fn():
}
}
}()
return dataStream
}
// Take return a chan whose values are tahken from another chan
func (c *Channel) Take(done <-chan any, valueStream <-chan any, number int) <-chan any {
takeStream := make(chan any)

View File

@@ -42,6 +42,28 @@ func TestRepeat(t *testing.T) {
assert.Equal(1, <-intStream)
}
func TestRepeatFn(t *testing.T) {
assert := internal.NewAssert(t, "TestRepeatFn")
done := make(chan any)
defer close(done)
fn := func() any {
s := "a"
return s
}
c := NewChannel()
dataStream := c.Take(done, c.RepeatFn(done, fn), 3)
// for v := range dataStream {
// t.Log(v) //a, a, a
// }
assert.Equal("a", <-dataStream)
assert.Equal("a", <-dataStream)
assert.Equal("a", <-dataStream)
}
func TestTake(t *testing.T) {
assert := internal.NewAssert(t, "TestRepeat")