This is a redux implementation in Go.
$ go get github.com/dannypsnl/redux
import (
// must import, else go module would think following package is a module
_ "github.com/dannypsnl/redux/v2"
// v2 store
"github.com/dannypsnl/redux/v2/store"
// v2 rematch(optional)
"github.com/dannypsnl/redux/v2/rematch"
)
Basic example
// As you can see, you don't need to checking nil or not now
// Now redux-go will initial the state with zero value of that type
func counter(state int, action string) int {
switch action {
case "INC":
return state + 1
case "DEC":
return state - 1
default:
return state
}
}
func main() {
// redux/v2/store
store := store.New(counter)
store.Dispatch("INC")
fmt.Printf("%d\n", store.StateOf(counter)) // should print out: 1
}
More stunning(lambda can work)
func main() {
counter := func(state, payload int) int {
return state + payload
}
store := store.New(counter)
store.Dispatch(100)
store.Dispatch(-50)
fmt.Printf("%d\n", store.StateOf(counter)) // should print out: 50
}
And more...
type CountingModel struct {
rematch.Reducer
State int
}
func (cm *CountingModel) Increase(s, payload int) int {
return s + payload
}
func (cm *CountingModel) Decrease(s, payload int) int {
return s - payload
}
func main() {
c := &CountingModel{
State: 0,
}
store := store.New(c)
store.Dispatch(c.Action(c.Increase).With(100))
store.Dispatch(c.Action(c.Decrease).With(50))
fmt.Printf("result: %d\n", store.StateOf(c)) // expect: 50
}
Then let's have a party
type CountingModel struct {
rematch.Reducer
State int
Increase *rematch.Action `action:"IncreaseImpl"`
}
func (c *CountingModel) IncreaseImpl(s, payload int) int {
return s + payload
}
func main() {
c := &CountingModel {
State: 0,
}
store := store.New(c)
store.Dispatch(c.Increase.With(30))
store.Dispatch(c.Increase.With(20))
fmt.Printf("result: %d\n", store.StateOf(c)) // expect: 50
}