From 5d556d8d74e60648567d59222b31a1245aa0ff3b Mon Sep 17 00:00:00 2001 From: laeo <8142123+laeo@users.noreply.github.com> Date: Wed, 30 Mar 2022 14:24:21 +0800 Subject: [PATCH] feat: add find and search --- find.go | 11 +++++++++++ find_test.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ search.go | 11 +++++++++++ search_test.go | 31 +++++++++++++++++++++++++++++++ 4 files changed, 102 insertions(+) create mode 100644 find.go create mode 100644 find_test.go create mode 100644 search.go create mode 100644 search_test.go diff --git a/find.go b/find.go new file mode 100644 index 0000000..476d234 --- /dev/null +++ b/find.go @@ -0,0 +1,11 @@ +package slice + +// Find finds by using function `fn` and returns its value. +func Find[T any](values []T, fn func(v T) bool) (v T, found bool) { + for i := 0; i < len(values); i++ { + if fn(values[i]) { + return values[i], true + } + } + return +} diff --git a/find_test.go b/find_test.go new file mode 100644 index 0000000..dcd0f57 --- /dev/null +++ b/find_test.go @@ -0,0 +1,49 @@ +package slice + +import ( + "reflect" + "testing" +) + +func TestFind(t *testing.T) { + type args struct { + values []int + fn func(v int) bool + } + tests := []struct { + name string + args args + wantV int + wantFound bool + }{ + { + name: "find_int_should_succeed", + args: args{ + values: []int{1, 2, 3, 4, 5}, + fn: func(v int) bool { return v == 5 }, + }, + wantV: 5, + wantFound: true, + }, + { + name: "find_int_should_failed", + args: args{ + values: []int{1, 2, 3, 4, 5}, + fn: func(v int) bool { return v == 6 }, + }, + wantV: 0, + wantFound: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotV, gotFound := Find(tt.args.values, tt.args.fn) + if !reflect.DeepEqual(gotV, tt.wantV) { + t.Errorf("Find() gotV = %v, want %v", gotV, tt.wantV) + } + if gotFound != tt.wantFound { + t.Errorf("Find() gotFound = %v, want %v", gotFound, tt.wantFound) + } + }) + } +} diff --git a/search.go b/search.go new file mode 100644 index 0000000..03d4b62 --- /dev/null +++ b/search.go @@ -0,0 +1,11 @@ +package slice + +// Search searches by using function `fn` and returns its index. +func Search[T any](values []T, fn func(v T) bool) int { + for i := 0; i < len(values); i++ { + if fn(values[i]) { + return i + } + } + return -1 +} diff --git a/search_test.go b/search_test.go new file mode 100644 index 0000000..498d8da --- /dev/null +++ b/search_test.go @@ -0,0 +1,31 @@ +package slice + +import "testing" + +func TestSearch(t *testing.T) { + type args struct { + values []int + fn func(v int) bool + } + tests := []struct { + name string + args args + want int + }{ + { + name: "search_int_should_succeed", + args: args{ + values: []int{1, 2, 3, 4, 5}, + fn: func(v int) bool { return v == 3 }, + }, + want: 2, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Search(tt.args.values, tt.args.fn); got != tt.want { + t.Errorf("Search() = %v, want %v", got, tt.want) + } + }) + } +}