Skip to content

Commit

Permalink
Add a tea.Sequentially command
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <caarlos0@gmail.com>
  • Loading branch information
caarlos0 authored and meowgorithm committed Jan 17, 2021
1 parent b65205a commit a0c6074
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
24 changes: 24 additions & 0 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,27 @@ func Tick(d time.Duration, fn func(time.Time) Msg) Cmd {
return fn(<-t.C)
}
}

// Sequentially produces a command that sequentially executes the given
// commands.
// The Msg returned is the first non-nil message returned by a Cmd.
//
// func saveStateCmd() Msg {
// if err := save(); err != nil {
// return errMsg{err}
// }
// return nil
// }
//
// cmd := Sequentially(saveStateCmd, Quit)
//
func Sequentially(cmds ...Cmd) Cmd {
return func() Msg {
for _, cmd := range cmds {
if msg := cmd(); msg != nil {
return msg
}
}
return nil
}
}
56 changes: 56 additions & 0 deletions commands_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package tea

import (
"fmt"
"testing"
)

func TestSequentially(t *testing.T) {
var expectedErrMsg = fmt.Errorf("some err")
var expectedStrMsg = "some msg"

var nilReturnCmd = func() Msg {
return nil
}

tests := []struct {
name string
cmds []Cmd
expected Msg
}{
{
name: "all nil",
cmds: []Cmd{nilReturnCmd, nilReturnCmd},
expected: nil,
},
{
name: "one error",
cmds: []Cmd{
nilReturnCmd,
func() Msg {
return expectedErrMsg
},
nilReturnCmd,
},
expected: expectedErrMsg,
},
{
name: "some msg",
cmds: []Cmd{
nilReturnCmd,
func() Msg {
return expectedStrMsg
},
nilReturnCmd,
},
expected: expectedStrMsg,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if msg := Sequentially(test.cmds...)(); msg != test.expected {
t.Fatalf("expected a msg %v but got %v", test.expected, msg)
}
})
}
}

0 comments on commit a0c6074

Please sign in to comment.