Skip to content

Commit

Permalink
add factory.ChainableModifier (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
aidenwallis authored May 26, 2023
1 parent a70778a commit 84e04b8
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
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)
}

0 comments on commit 84e04b8

Please sign in to comment.