From aef556796c31a045017f725709f77f868b6d7011 Mon Sep 17 00:00:00 2001 From: xing Date: Tue, 24 Jan 2023 00:16:47 +0800 Subject: [PATCH] unique New --- helper/slice/set.go | 12 ++++++++++++ helper/slice/set_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/helper/slice/set.go b/helper/slice/set.go index 8963d80..e9e7cf2 100644 --- a/helper/slice/set.go +++ b/helper/slice/set.go @@ -112,3 +112,15 @@ func UniqueByFn[T any](fn func(T, T) bool, a ...[]T) (r []T) { } return r } +func UniqueNewByFn[T, V any](fn func(T, T) bool, fnVal func(T) V, a ...[]T) (r []V) { + var rr []T + for _, ts := range a { + for _, t := range ts { + if !IsContainedByFn(rr, t, fn) { + rr = append(rr, t) + r = append(r, fnVal(t)) + } + } + } + return r +} diff --git a/helper/slice/set_test.go b/helper/slice/set_test.go index 3f2b151..d0400c1 100644 --- a/helper/slice/set_test.go +++ b/helper/slice/set_test.go @@ -218,3 +218,38 @@ func TestUniqueByFn(t *testing.T) { }) } } + +func TestUniqueNewByFn(t *testing.T) { + type args[T x, V int] struct { + fn func(T, T) bool + fnVal func(T) V + a [][]T + } + type testCase[T x, V int] struct { + name string + args args[T, V] + wantR []V + } + tests := []testCase[x, int]{ + { + name: "t1", + args: args[x, int]{ + fn: func(i, j x) bool { + return i.int == j.int + }, + fnVal: func(i x) int { + return i.int + }, + a: [][]x{y([]int{1, 1, 2, 2, 3, 3}), y([]int{2, 2, 4, 4})}, + }, + wantR: []int{1, 2, 3, 4}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if gotR := UniqueNewByFn(tt.args.fn, tt.args.fnVal, tt.args.a...); !reflect.DeepEqual(gotR, tt.wantR) { + t.Errorf("UniqueNewByFn() = %v, want %v", gotR, tt.wantR) + } + }) + } +}