1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-08 22:52:29 +08:00

feat: add example for enum package

This commit is contained in:
dudaodong
2025-10-14 16:37:02 +08:00
parent 3ac9461c00
commit cd43004a91
3 changed files with 318 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ import (
"encoding/json"
"fmt"
"reflect"
"sort"
"sync"
)
@@ -15,6 +16,7 @@ import (
type Enum[T comparable] interface {
Value() T
String() string
Name() string
Valid() bool
}
@@ -67,6 +69,10 @@ func (e *Item[T]) Name() string {
return e.name
}
func (e *Item[T]) String() string {
return e.name
}
// Valid checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
func (e *Item[T]) Valid(check ...func(T) bool) bool {
if len(check) > 0 {
@@ -280,3 +286,38 @@ func (r *Registry[T]) Size() int {
return len(r.items)
}
// Range iterates over all enum items in the registry and applies the given function.
func (r *Registry[T]) Range(fn func(*Item[T]) bool) {
r.mu.RLock()
defer r.mu.RUnlock()
for _, item := range r.items {
if !fn(item) {
break
}
}
}
// SortedItems returns a slice of all enum items sorted by the given less function.
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T] {
items := r.Items()
sort.Slice(items, func(i, j int) bool {
return less(items[i], items[j])
})
return items
}
// Filter returns a slice of enum items that satisfy the given predicate function.
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T] {
r.mu.RLock()
defer r.mu.RUnlock()
var result []*Item[T]
for _, item := range r.items {
if predicate(item) {
result = append(result, item)
}
}
return result
}