Skip to content

Commit

Permalink
feat: add find and search
Browse files Browse the repository at this point in the history
  • Loading branch information
laeo committed Mar 30, 2022
1 parent c37750b commit 5d556d8
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 0 deletions.
11 changes: 11 additions & 0 deletions find.go
Original file line number Diff line number Diff line change
@@ -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
}
49 changes: 49 additions & 0 deletions find_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
11 changes: 11 additions & 0 deletions search.go
Original file line number Diff line number Diff line change
@@ -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
}
31 changes: 31 additions & 0 deletions search_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit 5d556d8

Please sign in to comment.