github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/visitor.go (about) 1 package utils 2 3 // VisitAll runs all visitors and returns the final state 4 func VisitAll[VisitorState any]( 5 initial VisitorState, 6 visitors ...func(ctx *VisitorState), 7 ) VisitorState { 8 state := initial 9 for _, visitor := range visitors { 10 visitor(&state) 11 } 12 13 return state 14 } 15 16 // VisitCond runs all visitors if the condition is true and returns the final state 17 // If the condition is false, the visitor will stop and DO NOT run the rest of the visitors. 18 // cond function is called before each visitor. 19 // 20 // NOTE: `cond` is called before each visitor, hence, it will be run on initial state too. 21 func VisitCond[VisitorState any]( 22 initial VisitorState, 23 cond func(ctx *VisitorState) bool, 24 visitors ...func(ctx *VisitorState), 25 ) VisitorState { 26 state := initial 27 for _, visitor := range visitors { 28 if cond(&state) { 29 visitor(&state) 30 } 31 } 32 33 return state 34 } 35 36 // VisitStopOnErr runs all visitors and returns the final state 37 // If any of the visitors returns an error, the visitor will stop and DO NOT run the rest of the visitors. 38 // It returns the latest state and the error. 39 func VisitStopOnErr[VisitorState any]( 40 initial VisitorState, 41 visitors ...func(ctx *VisitorState) error, 42 ) (VisitorState, error) { 43 state := initial 44 for _, visitor := range visitors { 45 err := visitor(&state) 46 if err != nil { 47 return state, err 48 } 49 } 50 51 return state, nil 52 }