github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zarray/array_test.go (about) 1 package zarray_test 2 3 import ( 4 "testing" 5 6 zls "github.com/sohaha/zlsgo" 7 "github.com/sohaha/zlsgo/zarray" 8 ) 9 10 func TestArray(t *testing.T) { 11 tt := zls.NewTest(t) 12 var err error 13 array := zarray.New() 14 tt.Equal(true, array.IsEmpty()) 15 for i := 0; i < 10; i++ { 16 if err := array.Add(i, i+1); err != nil { 17 t.Error(err) 18 break 19 } 20 } 21 err = array.Add(99, "无效") 22 tt.Equal(true, err != nil) 23 _, err = array.Get(99) 24 tt.Equal(true, err != nil) 25 err = array.Set(99, "无效") 26 tt.Equal(true, err != nil) 27 _ = array.Unshift("第一") 28 array.Push("最后") 29 tt.Equal(true, array.Contains("第一")) 30 tt.Equal(false, array.Contains("第一百")) 31 tt.Equal(0, array.Index("第一")) 32 tt.Equal(-1, array.Index("第一百")) 33 tt.Equal(20, array.CapLength()) 34 tt.Equal(12, array.Length()) 35 last, _ := array.Get(0) 36 tt.Equal("第一", last) 37 _ = array.Set(0, "one") 38 one := []string{"one"} 39 shift, _ := array.Shift() 40 oneArr, _ := zarray.Copy(shift) 41 _ = array.Raw() 42 _, copyErr := zarray.Copy("shift") 43 tt.Equal(true, copyErr != nil) 44 tt.Equal(one[0], shift.([]interface{})[0]) 45 copyValue, _ := oneArr.Get(0) 46 tt.Equal(one[0], copyValue) 47 _, _ = array.Remove(99) 48 _, _ = array.RemoveValue("最后") 49 pop, _ := array.Pop() 50 tt.Equal(10, pop.([]interface{})[0]) 51 tt.Equal(9, array.Length()) 52 for i := 0; i < 9; i++ { 53 _, _ = array.Remove(i, 2) 54 } 55 array.Format() 56 tt.Equal(3, array.Length()) 57 array.Clear() 58 tt.Equal(0, array.Length()) 59 v, _ := array.Get(1991, "成功") 60 tt.Equal("成功", v) 61 62 array = zarray.New(100) 63 array = array.Map(func(i int, v interface{}) interface{} { 64 return i 65 }) 66 newArray := array.Shuffle() 67 t.Log(newArray.Raw()) 68 t.Log(array.Raw()) 69 } 70 71 var testdata = []interface{}{1, 2, 3, 4, 5, 6, 7} 72 73 func BenchmarkArrayNew(b *testing.B) { 74 arr, _ := zarray.Copy(testdata) 75 b.ReportAllocs() 76 b.ResetTimer() 77 b.RunParallel(func(pb *testing.PB) { 78 for pb.Next() { 79 for i := 0; i < 7; i++ { 80 v, _ := arr.Get(i) 81 _ = v 82 } 83 } 84 }) 85 } 86 87 func BenchmarkArrayRaw(b *testing.B) { 88 arr := testdata 89 b.ReportAllocs() 90 b.ResetTimer() 91 b.RunParallel(func(pb *testing.PB) { 92 for pb.Next() { 93 for i := 0; i < 7; i++ { 94 v := arr[i] 95 _ = v 96 } 97 } 98 }) 99 }