Skip to content

Commit

Permalink
✅ test: add test case
Browse files Browse the repository at this point in the history
🧹 chore: rename `AddEvent` to `Emit`
  • Loading branch information
jingyuexing committed Dec 31, 2023
1 parent afed59c commit 8ffdb55
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 17 deletions.
2 changes: 1 addition & 1 deletion emit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down
20 changes: 4 additions & 16 deletions options.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package utils

import "reflect"

type Options[T any] struct {
values T
none bool
Expand All @@ -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] {
Expand Down Expand Up @@ -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
}
Expand All @@ -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()
}
32 changes: 32 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

}

0 comments on commit 8ffdb55

Please sign in to comment.