From 25ed712fc9ba1f18fe2c1ce5524e2917160ae295 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 14 Jul 2023 21:24:27 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20super=20=E5=8C=85=E6=94=AF=E6=8C=81=20m?= =?UTF-8?q?atch=20=E6=8E=A7=E5=88=B6=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/super/match.go | 34 ++++++++++++++++++++++++++++++++++ utils/super/match_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 utils/super/match.go create mode 100644 utils/super/match_test.go diff --git a/utils/super/match.go b/utils/super/match.go new file mode 100644 index 0000000..4c83a8b --- /dev/null +++ b/utils/super/match.go @@ -0,0 +1,34 @@ +package super + +import "reflect" + +// Matcher 匹配器 +type Matcher[Value, Result any] struct { + value Value + r Result + d bool +} + +// Match 匹配 +func Match[Value, Result any](value Value) *Matcher[Value, Result] { + return &Matcher[Value, Result]{ + value: value, + } +} + +// Case 匹配 +func (slf *Matcher[Value, Result]) Case(value Value, result Result) *Matcher[Value, Result] { + if !slf.d && reflect.DeepEqual(slf.value, value) { + slf.r = result + slf.d = true + } + return slf +} + +// Default 默认 +func (slf *Matcher[Value, Result]) Default(value Result) Result { + if slf.d { + return slf.r + } + return value +} diff --git a/utils/super/match_test.go b/utils/super/match_test.go new file mode 100644 index 0000000..3f094c0 --- /dev/null +++ b/utils/super/match_test.go @@ -0,0 +1,24 @@ +package super_test + +import ( + "github.com/kercylan98/minotaur/utils/super" + . "github.com/smartystreets/goconvey/convey" + "testing" +) + +func TestMatch(t *testing.T) { + Convey("TestMatch", t, func() { + So(super.Match[int, string](1). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "a") + So(super.Match[int, string](2). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "b") + So(super.Match[int, string](3). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "c") + }) +}