You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
slices package provides useful Chunk function that batches a slice into chunks.
A fellow iter alternative would be extremely helpful to work with iterators.
Below is a sample implementation that I'm using in my projects (rewritten to fit into iter package):
package iter
// ...// ChunkIter works like slices.Chunk but with iterators,// i. e. iterates over it and yields batches of size n.// Panics if n is less than 1.funcChunkIter[ISeq[V], Vany](itI, nint) Seq[[]V] {
ifn<1 {
panic("cannot be less than 1")
}
returnfunc(yieldfunc([]V) bool) {
batch:= []V{}
forv:=rangeit {
batch=append(batch, v)
iflen(batch) ==n {
if!yield(batch) {
return
}
batch= []V{}
}
}
iflen(batch) >0 {
yield(batch)
}
}
}
// ChunkIter2 works like slices.ChunkIter,// but yields pairs of batches of size n.// Panics if n is less than 1.funcChunkIter2[ISeq2[K, V], Kany, Vany](itI, nint) Seq2[[]K, []V] {
ifn<1 {
panic("cannot be less than 1")
}
returnfunc(yieldfunc([]K, []V) bool) {
kbatch:= []K{}
vbatch:= []V{}
fork, v:=rangeit {
kbatch=append(kbatch, k)
vbatch=append(vbatch, v)
iflen(kbatch) ==n {
if!yield(kbatch, vbatch) {
return
}
kbatch= []K{}
vbatch= []V{}
}
}
iflen(kbatch) >0 {
yield(kbatch, vbatch)
}
}
}
Even though iterators are great, I would argue that implementing them results in code that is rather hard to read. Thus I find this snippet complex enough to be considered for addition into iter package.
Adding playground link that demonstrates and tests this implementation.
This is my first proposal for the gopher community, so please feel free to let me know if I should provide more details or update anything.
EDIT: After some consideration, I think ChunkSeq and ChunkSeq2 would probably be more appropriate than ChunkIter / ChunkIter2.
The text was updated successfully, but these errors were encountered:
Proposal Details
Proposal details
slices
package provides usefulChunk
function that batches a slice into chunks.A fellow
iter
alternative would be extremely helpful to work with iterators.Below is a sample implementation that I'm using in my projects (rewritten to fit into
iter
package):Even though iterators are great, I would argue that implementing them results in code that is rather hard to read. Thus I find this snippet complex enough to be considered for addition into
iter
package.Adding playground link that demonstrates and tests this implementation.
This is my first proposal for the gopher community, so please feel free to let me know if I should provide more details or update anything.
EDIT: After some consideration, I think
ChunkSeq
andChunkSeq2
would probably be more appropriate thanChunkIter
/ChunkIter2
.The text was updated successfully, but these errors were encountered: