Created
April 6, 2021 06:49
-
-
Save islishude/ed889aa14f877ee5d9e4b551c6286587 to your computer and use it in GitHub Desktop.
steam chunk for golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"os" | |
) | |
func main() { | |
stream := make(chan int, 1) | |
go func() { | |
defer close(stream) | |
for i := 0; i < 6; i++ { | |
stream <- i | |
} | |
}() | |
const maxLength = 5 | |
const minLength = 1 | |
result := make([][]int, 0, 10) | |
buffer := make([]int, 0, maxLength) | |
for i := range stream { | |
if len(buffer) == maxLength-1 { | |
result = append(result, append(buffer, i)) | |
buffer = make([]int, 0, maxLength) | |
continue | |
} | |
buffer = append(buffer, i) | |
} | |
if len(buffer) >= minLength { | |
result = append(result, buffer) | |
} | |
_ = json.NewEncoder(os.Stdout).Encode(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment