-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype_adapter_action.go
More file actions
52 lines (43 loc) · 1.58 KB
/
Copy pathtype_adapter_action.go
File metadata and controls
52 lines (43 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package chain
import "context"
// InternalTypeGetter extracts a subpart (U) from a composite data structure (T).
// It allows access to a part of the structure without modifying the entire one.
type InternalTypeGetter[T any, U any] func(T) U
// ExternalTypeSetter updates a composite data structure (T) with a new subpart (U).
// It returns the updated composite value.
type ExternalTypeSetter[T any, U any] func(T, U) T
// AdaptAction creates an Action that works with a composite data structure (T),
// where T is a complex type (e.g., a struct with multiple fields) and U is the
// data type that the Action operates on. The InternalTypeGetter and ExternalTypeSetter
// functions extract U from T and write the processed result back into T.
func AdaptAction[T any, U any](
action Action[U],
getter InternalTypeGetter[T, U],
setter ExternalTypeSetter[T, U],
) Action[T] {
if action == nil {
panic("action cannot be nil")
} else if getter == nil {
panic("getter cannot be nil")
} else if setter == nil {
panic("setter cannot be nil")
}
return &typeAdapterAction[T, U]{
action: action,
getter: getter,
setter: setter,
}
}
type typeAdapterAction[T any, U any] struct {
action Action[U]
getter InternalTypeGetter[T, U]
setter ExternalTypeSetter[T, U]
}
func (a typeAdapterAction[T, U]) Name() string { return a.action.Name() }
func (a typeAdapterAction[T, U]) Run(ctx context.Context, input T) (output T, err error) {
output = input
actualInput := a.getter(input)
actualOutput, err := a.action.Run(ctx, actualInput)
output = a.setter(output, actualOutput)
return output, err
}