-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
114 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package utils | ||
|
||
// VisitAll runs all visitors and returns the final state | ||
func VisitAll[VisitorState any]( | ||
initial VisitorState, | ||
visitors ...func(ctx *VisitorState), | ||
) VisitorState { | ||
state := initial | ||
for _, visitor := range visitors { | ||
visitor(&state) | ||
} | ||
|
||
return state | ||
} | ||
|
||
// VisitCond runs all visitors if the condition is true and returns the final state | ||
// If the condition is false, the visitor will stop and DO NOT run the rest of the visitors. | ||
// cond function is called before each visitor. | ||
// | ||
// NOTE: `cond` is called before each visitor, hence, it will be run on initial state too. | ||
func VisitCond[VisitorState any]( | ||
initial VisitorState, | ||
cond func(ctx *VisitorState) bool, | ||
visitors ...func(ctx *VisitorState), | ||
) VisitorState { | ||
state := initial | ||
for _, visitor := range visitors { | ||
if cond(&state) { | ||
visitor(&state) | ||
} | ||
} | ||
|
||
return state | ||
} | ||
|
||
// VisitStopOnErr runs all visitors and returns the final state | ||
// If any of the visitors returns an error, the visitor will stop and DO NOT run the rest of the visitors. | ||
// It returns the latest state and the error. | ||
func VisitStopOnErr[VisitorState any]( | ||
initial VisitorState, | ||
visitors ...func(ctx *VisitorState) error, | ||
) (VisitorState, error) { | ||
state := initial | ||
for _, visitor := range visitors { | ||
err := visitor(&state) | ||
if err != nil { | ||
return state, err | ||
} | ||
} | ||
|
||
return state, nil | ||
} |