Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds factory.ChainableModifier #25

Merged
merged 1 commit into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions factory/chainable_modifier.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package factory

// ChainableModifier creates a factory that produces an initial value from initFactory, then lets you change modifiers to modify that value.
// You're then returned the value once all modifiers have ran over it. This can be particularly useful when building mock data in tests.
//
// func example() {
// chain := ChainableModifier(func() *pb.MyRequest {
// return &pb.MyRequest{Foo: true, Bar: false}
// })
//
// firstRequest := chain() // returns &pb.MyRequest{Foo: true, Bar: false}
//
// secondRequestWithBarTrue := chain(func(v *pb.MyRequest) {
// v.Bar = true
// }) // returns &pb.MyRequest{Foo: true, Bar: true}
//
// thirdRequestWithValuesSwapped := chain(func(v *pb.MyRequest) {
// v.Foo = false
// }, func(v *pb.MyRequest) {
// v.Bar = true
// }) // returns &pb.MyRequest{Foo: false, Bar: true}
// }
func ChainableModifier[T any](initFactory func() T) func(modifiers ...func(T)) T {
return func(modifiers ...func(T)) T {
out := initFactory()

for _, fn := range modifiers {
fn(out)
}

return out
}
}
30 changes: 30 additions & 0 deletions factory/chainable_modifier_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package factory_test

import (
"testing"

"github.com/aidenwallis/go-utils/factory"
"github.com/aidenwallis/go-utils/internal/assert"
)

func TestChainableModifier(t *testing.T) {
t.Parallel()

type testValue struct {
Foo bool
Bar bool
}

chain := factory.ChainableModifier(func() *testValue {
return &testValue{
Foo: true,
Bar: false,
}
})

out := chain(func(v *testValue) {
v.Foo = false
})
assert.False(t, out.Foo)
assert.False(t, out.Bar)
}