0
0

Go のリスト分割

Last updated at Posted at 2024-08-13

リストを指定のサイズで分割して返す関数を用意した。
誰かが使うかも知れないので、共有しておく。誰も使わなかったら自分で使おう。

func Split[T any](elms []T, size int) [][]T {
	if size <= 0 {
		return [][]T{elms}
	}
	var split [][]T
	for 0 < len(elms) {
		s := size
		if len(elms) < size {
			s = len(elms)
		}
		split = append(split, elms[0:s])
		elms = elms[s:]
	}
	return split
}

テストケースも併せて用意。

func TestSplit(t *testing.T) {
	tests := []struct {
		name string
		elms []string
		size int
		want [][]string
	}{
		{
			name: "partial",
			elms: []string{"a", "b", "c", "d", "e"},
			size: 2,
			want: [][]string{{"a", "b"}, {"c", "d"}, {"e"}},
		},
		{
			name: "just",
			elms: []string{"a", "b", "c", "d", "e", "f"},
			size: 2,
			want: [][]string{{"a", "b"}, {"c", "d"}, {"e", "f"}},
		},
		{
			name: "single element",
			elms: []string{"a"},
			size: 2,
			want: [][]string{{"a"}},
		},
		{
			name: "empty",
			elms: []string{},
			size: 2,
			want: nil,
		},
		{
			name: "nil",
			elms: nil,
			size: 2,
			want: nil,
		},
		{
			name: "size: 1",
			elms: []string{"a", "b", "c", "d", "e"},
			size: 1,
			want: [][]string{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}},
		},
		{
			name: "size: 0",
			elms: []string{"a", "b", "c", "d", "e"},
			size: 0,
			want: [][]string{{"a", "b", "c", "d", "e"}},
		},
		{
			name: "size: -1",
			elms: []string{"a", "b", "c", "d", "e"},
			size: 0,
			want: [][]string{{"a", "b", "c", "d", "e"}},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := Split(tt.elms, tt.size)
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("Split() = %v, want %v", got, tt.want)
			}
		})
	}
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0