Created
February 5, 2019 07:00
-
-
Save mustafaturan/7a29e8251a7369645fb6c2965f8c2daf to your computer and use it in GitHub Desktop.
Go / Chunk Slice
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
# https://play.golang.org/p/JxqibtHkuO- | |
func chunkBy(items []string, chunkSize int) (chunks [][]string) { | |
for chunkSize < len(items) { | |
items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize]) | |
} | |
return append(chunks, items) | |
} |
Nice!
You can allocate memory use make() like
var chunks = make([][]string, 0, len(items) / chunkSize + 1)
// or
// if use this variant, need to be add index into cycle and access via index
var chunks = make([][]string, len(items) / chunkSize + 1)
And you can do like that
this
items[0:chunkSize:chunkSize]
to
items[:chunkSize:chunkSize]
Nice! Thanks to your code + @kamnev8823 suggestion, here's my final code I shared on StackOverflow (it includes generics support): https://stackoverflow.com/a/72408490/3971297
thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks