1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-06 13:42:28 +08:00

feat: add DifferenceWith

This commit is contained in:
dudaodong
2022-01-24 14:53:45 +08:00
parent 89aef977a2
commit 18ec73839b
2 changed files with 40 additions and 4 deletions

View File

@@ -126,6 +126,31 @@ func DifferenceBy[T any](slice []T, comparedSlice []T, iteratee func(index int,
return res
}
//DifferenceWith accepts comparator which is invoked to compare elements of slice to values. The order and references of result values are determined by the first slice. The comparator is invoked with two arguments: (arrVal, othVal).
func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(value, otherValue T) bool) []T {
res := make([]T, 0, 0)
getIndex := func(arr []T, item T, comparison func(v1, v2 T) bool) int {
index := -1
for i, v := range arr {
if comparison(item, v) {
index = i
break
}
}
return index
}
for i, v := range slice {
index := getIndex(comparedSlice, v, comparator)
if index == -1 {
res = append(res, slice[i])
}
}
return res
}
// Every return true if all of the values in the slice pass the predicate function.
func Every[T any](slice []T, predicate func(index int, t T) bool) bool {
if predicate == nil {

View File

@@ -380,7 +380,7 @@ func TestIntersection(t *testing.T) {
}
func TestReverse(t *testing.T) {
assert := internal.NewAssert(t, "TestIntersection")
assert := internal.NewAssert(t, "TestReverse")
s1 := []int{1, 2, 3, 4, 5}
Reverse(s1)
@@ -392,13 +392,24 @@ func TestReverse(t *testing.T) {
}
func TestDifference(t *testing.T) {
assert := internal.NewAssert(t, "TestIntersection")
assert := internal.NewAssert(t, "TestDifference")
s1 := []int{1, 2, 3, 4, 5}
s2 := []int{4, 5, 6}
assert.Equal([]int{1, 2, 3}, Difference(s1, s2))
}
func TestDifferenceWith(t *testing.T) {
assert := internal.NewAssert(t, "TestDifferenceWith")
s1 := []int{1, 2, 3, 4, 5}
s2 := []int{4, 5, 6, 7, 8}
isDouble := func(v1, v2 int) bool {
return v2 == 2*v1
}
assert.Equal([]int{1, 5}, DifferenceWith(s1, s2, isDouble))
}
func TestDifferenceBy(t *testing.T) {
assert := internal.NewAssert(t, "TestDifferenceBy")
@@ -411,7 +422,7 @@ func TestDifferenceBy(t *testing.T) {
}
func TestSortByFielDesc(t *testing.T) {
assert := internal.NewAssert(t, "TestWithout")
assert := internal.NewAssert(t, "TestSortByFielDesc")
type student struct {
name string
@@ -437,7 +448,7 @@ func TestSortByFielDesc(t *testing.T) {
}
func TestSortByFieldAsc(t *testing.T) {
assert := internal.NewAssert(t, "TestSortByField")
assert := internal.NewAssert(t, "TestSortByFieldAsc")
type student struct {
name string