Skip to content

Commit

Permalink
Merge pull request #10 from orsinium-labs/parse-examples
Browse files Browse the repository at this point in the history
Provide examples for enum.Parse
  • Loading branch information
orsinium authored Apr 12, 2024
2 parents 2a22286 + 74393ed commit 4d8fb06
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
10 changes: 3 additions & 7 deletions enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ type Member[T comparable] struct {
Value T
}

// Equaler provides the customr comparator for value type.
// Equaler check if the two values of the same type are equal.
type Equaler[V comparable] interface {
Equal(v V) bool
Equal(other V) bool
comparable
}

Expand Down Expand Up @@ -156,11 +156,7 @@ func (e Enum[M, V]) GoString() string {
return fmt.Sprintf("enum.New(%s)", joined)
}

// Parse converts a raw value into a member like Enum.Parse. But,
// this returns the equal member by Equal().
//
// This is especially beneficial when the value type is struct, which
// means that be able to implement a custom comparator.
// Parse is like [Enum.Parse] but finds the member for the value using [Equaler] comparator.
func Parse[M iMember[V], V Equaler[V]](e Enum[M, V], value V) *M {
for v, m := range e.v2m {
if v.Equal(value) {
Expand Down
1 change: 1 addition & 0 deletions enum_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ type BookValue struct {
Title string
ISBN string
}

type Book enum.Member[BookValue]

var (
Expand Down
25 changes: 25 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package enum_test

import (
"fmt"
"strings"

"github.com/orsinium-labs/enum"
)
Expand Down Expand Up @@ -201,3 +202,27 @@ func ExampleNewBuilder() {
// Output:
// true true true
}

type FoldedString string

// Equal implements [enum.Equaler].
//
// Compare strings ignoring the case.
func (s FoldedString) Equal(other FoldedString) bool {
return strings.EqualFold(string(s), string(other))
}

func ExampleParse() {
type Color enum.Member[FoldedString]

var (
Red = Color{"red"}
Green = Color{"green"}
Blue = Color{"blue"}
Colors = enum.New(Red, Green, Blue)
)

parsed := enum.Parse(Colors, "RED")
fmt.Printf("%#v\n", parsed)
// Output: &enum_test.Color{Value:"red"}
}

0 comments on commit 4d8fb06

Please sign in to comment.