From e4376a39b40c84916c5c78b1e3b3c74217be6d16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flc=E3=82=9B?= Date: Wed, 6 Mar 2024 20:26:15 +0800 Subject: [PATCH] feat(helper): Add Chain (#134) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Flcă‚› --- helper/helper.go | 9 +++++++++ helper/helper_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/helper/helper.go b/helper/helper.go index f4c4a4a1..66049695 100644 --- a/helper/helper.go +++ b/helper/helper.go @@ -24,6 +24,15 @@ func With[T any](value T, callbacks ...func(T) T) T { return value } +func Chain[T any](fns ...func(T) T) func(T) T { + return func(v T) T { + for _, fn := range fns { + v = fn(v) + } + return v + } +} + func When[T any](value T, condition bool, callbacks ...func(T) T) T { if condition { return With(value, callbacks...) diff --git a/helper/helper_test.go b/helper/helper_test.go index 139f7b8c..fed23994 100644 --- a/helper/helper_test.go +++ b/helper/helper_test.go @@ -120,6 +120,43 @@ func TestWhen(t *testing.T) { assert.Equal(t, 18, f3.Age) } +func TestChain(t *testing.T) { + // chain functions + chain := Chain( + func(s string) string { + return s + "1" + }, + func(s string) string { + return s + "2" + }, + func(s string) string { + return s + "3" + }, + ) + + assert.Equal(t, "0123", chain("0")) + + // chain functions + chain2 := Chain( + func(foo *foo) *foo { + foo.Name = "bar" + return foo + }, + func(foo *foo) *foo { + foo.Age = 18 + return foo + }, + ) + + f := &foo{Name: "foo"} + assert.Equal(t, "foo", f.Name) + assert.Equal(t, 0, f.Age) + + got := chain2(f) + assert.Equal(t, "bar", got.Name) + assert.Equal(t, 18, got.Age) +} + func TestScan_Basic(t *testing.T) { // string var foo string