diff options
author | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-06-07 19:33:07 +0200 |
---|---|---|
committer | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-06-07 19:33:07 +0200 |
commit | c7a8aa113a914e70e027fea93265c7232b865b5e (patch) | |
tree | d5514cb6e5f49838ff75e814b64652ad244cf0ef /pkg/u | |
parent | 18aa098f50e2a2c7db01dd4d04dde460fd40f5d5 (diff) | |
download | cerrado-c7a8aa113a914e70e027fea93265c7232b865b5e.tar.gz cerrado-c7a8aa113a914e70e027fea93265c7232b865b5e.tar.bz2 cerrado-c7a8aa113a914e70e027fea93265c7232b865b5e.zip |
feat: Add compression
Diffstat (limited to 'pkg/u')
-rw-r--r-- | pkg/u/list.go | 8 | ||||
-rw-r--r-- | pkg/u/list_test.go | 35 |
2 files changed, 43 insertions, 0 deletions
diff --git a/pkg/u/list.go b/pkg/u/list.go index 34eafd1..cf71909 100644 --- a/pkg/u/list.go +++ b/pkg/u/list.go @@ -8,6 +8,14 @@ func First[T any](v []T) (T, bool) { return v[0], true } +func FirstOrZero[T any](v []T) T { + if len(v) == 0 { + var zero T + return zero + } + return v[0] +} + func ChunkBy[T any](items []T, chunkSize int) [][]T { var chunks = make([][]T, 0, (len(items)/chunkSize)+1) for chunkSize < len(items) { diff --git a/pkg/u/list_test.go b/pkg/u/list_test.go index a6d84c7..805a209 100644 --- a/pkg/u/list_test.go +++ b/pkg/u/list_test.go @@ -94,3 +94,38 @@ func TestSubList(t *testing.T) { }) } } + +func TestFirstOrZero(t *testing.T) { + testCases := []struct { + name string + slice []int + first int + }{ + { + name: "multiple items slice", + slice: []int{1, 2, 3}, + first: 1, + }, + { + name: "single item slice", + slice: []int{1}, + first: 1, + }, + { + name: "empty slice", + slice: []int{}, + first: 0, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + + first := FirstOrZero(tc.slice) + + if first != tc.first { + t.Errorf("Error first, want %d got %d", tc.first, first) + } + + }) + } +} |