batch

tiny golang package for pagination-style batching of slices
Log | Files | Refs | README | LICENSE

batch.go (1021B)


      1 // Package batch provides helper functions for batching slices into sub slices of a
      2 // specified length. You could think of it as pagination for slices.
      3 package batch
      4 
      5 import (
      6 	"math"
      7 	"strings"
      8 )
      9 
     10 // Str accepts a slice of strings and a page size, then splits up the slice
     11 // into smaller slices of length "pageSize"
     12 func Str(s []string, pageSize int) [][]string {
     13 
     14 	// math.Ceil only works properly with floats :(
     15 	size := int(math.Ceil(float64(len(s)) / float64(pageSize)))
     16 	output := make([][]string, size)
     17 	j := 0
     18 
     19 	for i := 0; i < len(s); i += pageSize {
     20 		end := i + pageSize
     21 		if end > len(s) {
     22 			end = len(s)
     23 		}
     24 		output[j] = s[i:end]
     25 		j++
     26 	}
     27 	return output
     28 }
     29 
     30 // StrJoin is a combination of Str() and strings.Join(). Rather than returning
     31 // a slice of slices, it returns a slice of joined strings
     32 func StrJoin(s []string, pageSize int, delimiter string) []string {
     33 	var output []string
     34 	for _, slice := range Str(s, pageSize) {
     35 		output = append(output, strings.Join(slice, delimiter))
     36 	}
     37 	return output
     38 }