Skip to content

Commit

Permalink
Split utility added
Browse files Browse the repository at this point in the history
  • Loading branch information
markdicksonjr committed Jun 17, 2019
1 parent 7194544 commit 1c0fe35
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions split.go
Original file line number Diff line number Diff line change
@@ -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
}
29 changes: 29 additions & 0 deletions split_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit 1c0fe35

Please sign in to comment.