diff --git a/README.md b/README.md index 47dc3012..0eac9bfe 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,14 @@ [![tests](https://github.com/go-kratos-ecosystem/components/actions/workflows/test.yml/badge.svg)](https://github.com/go-kratos-ecosystem/components/actions/workflows/test.yml) [![MIT license](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) +> ⚠️ **Note:** `v2.x` may introduce situations that are not backward compatible. +> +> When releasing a new version, backward compatibility is the default behavior. If there are any incompatibilities, they will be indicated in the release notes. +> +> This is expected to be improved in the `v3.x` version. +> +> Thanks. 😄 + ## Installation ```bash diff --git a/helpers/helpers.go b/helpers/helpers.go index 5703a518..3cbeca5a 100644 --- a/helpers/helpers.go +++ b/helpers/helpers.go @@ -4,6 +4,12 @@ import ( "encoding/json" ) +// If returns trueVal if condition is true, otherwise falseVal +// +// Example: +// +// If(true, "foo", "bar") // "foo" +// If(false, "foo", "bar") // "bar" func If[T any](condition bool, trueVal T, falseVal T) T { if condition { return trueVal @@ -12,6 +18,15 @@ func If[T any](condition bool, trueVal T, falseVal T) T { return falseVal } +// Tap calls the given callback with the given value then returns the value. +// +// Example: +// +// Tap("foo", func(s string) { +// fmt.Println(s) // "foo" and os.Stdout will print "foo" +// }, func(s string) { +// // more callbacks +// }...) func Tap[T any](value T, callbacks ...func(T)) T { for _, callback := range callbacks { if callback != nil { @@ -22,6 +37,15 @@ func Tap[T any](value T, callbacks ...func(T)) T { return value } +// With calls the given callbacks with the given value then return the value. +// +// Example: +// +// With("foo", func(s string) string { +// return s + "bar" +// }, func(s string) string { +// return s + "baz" +// }) // "foobarbaz" func With[T any](value T, callbacks ...func(T) T) T { for _, callback := range callbacks { if callback != nil { @@ -90,6 +114,15 @@ func ChainWithErr[T any](fns ...func(T) (T, error)) func(T) (T, error) { } } +// When calls the given callbacks with the given value if condition is true then return the value. +// +// Example: +// +// When("foo", true, func(s string) string { +// return s + "bar" +// }, func(s string) string { +// return s + "baz" +// }) // "foobarbaz" func When[T any](value T, condition bool, callbacks ...func(T) T) T { if condition { return With(value, callbacks...) @@ -98,6 +131,15 @@ func When[T any](value T, condition bool, callbacks ...func(T) T) T { return value } +// Scan sets the value of dest to the value of src. +// +// Example: +// +// var foo string +// Scan("bar", &foo) // foo == "bar" +// +// var bar struct {A string} +// Scan(struct{A string}{"foo"}, &bar) // bar == struct{A string}{"foo"} func Scan(src any, dest any) error { bytes, err := json.Marshal(src) if err != nil {