github.com/searKing/golang/go@v1.2.117/exp/slices/group_test.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slices_test 6 7 import ( 8 "slices" 9 "testing" 10 11 slices_ "github.com/searKing/golang/go/exp/slices" 12 ) 13 14 var groupTests = []struct { 15 s []int 16 want map[int]int 17 }{ 18 {nil, nil}, 19 {[]int{}, map[int]int{}}, 20 {[]int{1}, map[int]int{1: 1}}, 21 {[]int{1, 1}, map[int]int{1: 2}}, 22 {[]int{1, 2, 3}, map[int]int{1: 1, 2: 1, 3: 1}}, 23 {[]int{1, 1, 2, 3, 3}, map[int]int{1: 2, 2: 1, 3: 2}}, 24 {[]int{1, 2, 3, 4}, map[int]int{1: 1, 2: 1, 3: 1, 4: 1}}, 25 {[]int{1, 2, 3, 4, 2, 4, 2}, map[int]int{1: 1, 2: 3, 3: 1, 4: 2}}, 26 } 27 28 func TestGroup(t *testing.T) { 29 for i, test := range groupTests { 30 got := slices_.Group(test.s) 31 if len(test.want) != len(got) { 32 t.Errorf("#%d: Group(%v) = %v, want %v", i, test.s, got, test.want) 33 continue 34 } 35 for k := range got { 36 if got[k] != test.want[k] { 37 t.Errorf("#%d: Group(%v) = %v, want %v", i, test.s, got, test.want) 38 break 39 } 40 } 41 } 42 } 43 44 var groupFuncTests = []struct { 45 s []int 46 want map[int][]int 47 }{ 48 {nil, nil}, 49 {[]int{}, map[int][]int{}}, 50 {[]int{1}, map[int][]int{1: {1}}}, 51 {[]int{1, 1}, map[int][]int{1: {1, 1}}}, 52 {[]int{1, 2, 3}, map[int][]int{1: {1}, 2: {2}, 3: {3}}}, 53 {[]int{1, 1, 2, 3, 3}, map[int][]int{1: {1, 1}, 2: {2}, 3: {3, 3}}}, 54 {[]int{1, 2, 3, 4}, map[int][]int{1: {1}, 2: {2}, 3: {3}, 4: {4}}}, 55 {[]int{1, 2, 3, 4, 2, 4, 2}, map[int][]int{1: {1}, 2: {2, 2, 2}, 3: {3}, 4: {4, 4}}}, 56 } 57 58 func TestGroupFunc(t *testing.T) { 59 for i, test := range groupFuncTests { 60 got := slices_.GroupFunc(test.s, func(i int) int { return i }) 61 if len(test.want) != len(got) { 62 t.Errorf("#%d: Group(%v) = %v, want %v", i, test.s, got, test.want) 63 continue 64 } 65 for k := range got { 66 if !slices.Equal(got[k], test.want[k]) { 67 t.Errorf("#%d: Group(%v) = %v, want %v", i, test.s, got, test.want) 68 break 69 } 70 } 71 } 72 }