diff --git a/split.go b/split.go new file mode 100644 index 0000000..841d9de --- /dev/null +++ b/split.go @@ -0,0 +1,25 @@ +package work + +import "math" + +func Split(data []interface{}, parts int) [][]interface{} { + if parts < 2 { + return [][]interface{}{ data } + } + + // compute how large parts are + subLen := math.Floor(float64(len(data) / parts)) + + // build the returned result + results := make([][]interface{}, parts) + + // loop through data and slice out the evenly-sized parts + for i := 0; i < parts - 1; i++ { + results[i] = data[int(subLen) * i:int(subLen) * i + int(subLen)] + } + + // grab the end, which is the remainder-sized slice + results[parts - 1] = data[(parts - 1) * int(subLen):] + + return results +} diff --git a/split_test.go b/split_test.go new file mode 100644 index 0000000..7657abd --- /dev/null +++ b/split_test.go @@ -0,0 +1,29 @@ +package work + +import "testing" + +func TestSplit(t *testing.T) { + val := []interface{} { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } + res := Split(val, 5) + if len(res) != 5 { + t.Fatal("the number of parts was not 5") + } + + existsMap := make(map[int]bool) + sizeSum := 0 + for _, v := range res { + sizeSum += len(v) + + for _, i := range v { + existsMap[i.(int)] = true + } + } + + if sizeSum != 12 { + t.Fatal("the size of the result was not 12") + } + + if len(existsMap) != 12 { + t.Fatal("there were not 12 unique values, as expected") + } +}