From 74393edad618f88e8c4dc432f8ed42e3420ff54b Mon Sep 17 00:00:00 2001 From: gram Date: Fri, 12 Apr 2024 14:17:39 +0200 Subject: [PATCH] Provide examples for enum.Parse --- enum.go | 10 +++------- enum_test.go | 1 + example_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/enum.go b/enum.go index e2cb040..8f91a24 100644 --- a/enum.go +++ b/enum.go @@ -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 } @@ -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) { diff --git a/enum_test.go b/enum_test.go index 4b36889..e60215a 100644 --- a/enum_test.go +++ b/enum_test.go @@ -130,6 +130,7 @@ type BookValue struct { Title string ISBN string } + type Book enum.Member[BookValue] var ( diff --git a/example_test.go b/example_test.go index 30a86bf..eb6604f 100644 --- a/example_test.go +++ b/example_test.go @@ -2,6 +2,7 @@ package enum_test import ( "fmt" + "strings" "github.com/orsinium-labs/enum" ) @@ -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"} +}