From 8ffdb5588514af525257d1bef0e57032ddddff34 Mon Sep 17 00:00:00 2001 From: jingyuexing <19589872+jingyuexing@users.noreply.github.com> Date: Sun, 31 Dec 2023 18:19:46 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=85=20test:=20add=20test=20case=20?= =?UTF-8?q?=F0=9F=A7=B9=20chore:=20rename=20`AddEvent`=20to=20`Emit`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- emit.go | 2 +- options.go | 20 ++++---------------- utils_test.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/emit.go b/emit.go index 77946af..9166ab3 100644 --- a/emit.go +++ b/emit.go @@ -40,7 +40,7 @@ func (e *EventEmit) On(name string, callback func(args ...any)) { defer e.mutex.Unlock() } -func (e *EventEmit) AddEvent(name string, args ...any) { +func (e *EventEmit) Emit(name string, args ...any) { e.mutex.Lock() for _, call := range e.events[name] { call(args...) diff --git a/options.go b/options.go index 6ba16b5..0b01cc0 100644 --- a/options.go +++ b/options.go @@ -1,5 +1,7 @@ package utils +import "reflect" + type Options[T any] struct { values T none bool @@ -16,7 +18,7 @@ type OptionInterface[T any] interface { } func Some[T any](value T) Options[T] { - return Options[T]{values: value, none: false} + return Options[T]{values: value, none: reflect.ValueOf(value).IsZero()} } func None[T any]() Options[T] { @@ -45,7 +47,7 @@ func (o Options[T]) Expect(msg string) T { return o.values } -func (o Options[T]) UnwrapOr(defaultValue T) T { +func (o Options[T]) UnwrapOr(defaultValue any) any { if o.none { return defaultValue } @@ -70,17 +72,3 @@ func Option[T any](value T) Options[T] { return Some[T](value) } } -type People struct { - Age int - Name string - Address string -} - -func main(){ - somePeople := Option(&People{ - Age: 20, - Name: "Gog", - Address: "Mars", - }) - somePeople.Unwrap() -} diff --git a/utils_test.go b/utils_test.go index 7b2683b..6041c5f 100644 --- a/utils_test.go +++ b/utils_test.go @@ -100,3 +100,35 @@ func TestReduce(t *testing.T) { t.Error("not pass") } } + +func TestOption(t *testing.T) { + type S struct {} + v := &S{} + v = nil + raw := utils.Some(v) + + if !raw.IsNone() { + t.Error("not pass") + } + if raw.UnwrapOr(12).(int) != 12 { + t.Error("not pass") + } + +} + +func TestEmit(t *testing.T){ + event := utils.NewEventEmit() + count := 1 + event.On("plus",func(args ...any) { + count+= (args[0]).(int) + }) + + for i := 1; i <= 3; i++ { + event.Emit("plus",i) + } + + if count != 7 { + t.Error("not pass") + } + +}