Skip to content

Instantly share code, notes, and snippets.

@risentveber
Last active September 2, 2020 15:45
Show Gist options
  • Save risentveber/6a274ff145e6e952f9386b2038b22c30 to your computer and use it in GitHub Desktop.
Save risentveber/6a274ff145e6e952f9386b2038b22c30 to your computer and use it in GitHub Desktop.
func NewDynamicallyBufferedChannel(in <- chan interface{}) <- chan interface{} {
out := make(chan interface{})
var storage []interface{}
go func() {
defer close(out)
for {
if len(storage) == 0 {
item, ok := <-in
if !ok {
return
}
storage = append(storage, item)
continue
}
select {
case item, ok := <- in:
if ok {
storage = append(storage, item)
} else {
// unwind storage
for _, item := range storage {
out <- item
}
return
}
case out <- storage[0]:
if len(storage) == 1 {
storage = nil
} else {
storage = storage[1:]
}
}
}
}()
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment