Created
September 14, 2023 15:14
-
-
Save jonmorehouse/571ef27a0fd399053929f0c40ce1f239 to your computer and use it in GitHub Desktop.
Revisions
-
jonmorehouse created this gist
Sep 14, 2023 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,48 @@ package main import "fmt" func SliceToGroupsUpdated[T any](slice []T, limit int) [][]T { if limit < 1 { limit = 1 } matrix := [][]T{{}} row := 0 for _, val := range slice { matrix[row] = append(matrix[row], val) if len(matrix[row]) == limit { row++ matrix = append(matrix, []T{}) } } return matrix } func SliceToGroupsOrig[T any](vals []T, grpSize int) [][]T { if grpSize < 1 { grpSize = 1 } grps := make([][]T, 0) grp := make([]T, 0, grpSize) for _, val := range vals { grp = append(grp, val) if len(grp) >= grpSize { grps = append(grps, grp) grp = make([]T, 0, grpSize) } } return grps } func main() { grps := SliceToGroupsUpdated([]string{"a", "b", "c"}, 0) fmt.Println("updated", grps) grps = SliceToGroupsOrig([]string{"a", "b", "c"}, 0) fmt.Println("original", grps) }