From 9a06319ff1132013f212e00524ca006e2cce91ac Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Thu, 3 Feb 2022 12:08:34 -0300 Subject: [PATCH] feat: tea.Batch returns nil if all cmds are nil (#217) Signed-off-by: Carlos A Becker --- commands_test.go | 25 +++++++++++++++++++++++++ tea.go | 11 +++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/commands_test.go b/commands_test.go index 749c6a910d..e0d5ff3c38 100644 --- a/commands_test.go +++ b/commands_test.go @@ -80,3 +80,28 @@ func TestSequentially(t *testing.T) { }) } } + +func TestBatch(t *testing.T) { + t.Run("nil cmd", func(t *testing.T) { + if b := Batch(nil); b != nil { + t.Fatalf("expected nil, got %+v", b) + } + }) + t.Run("empty cmd", func(t *testing.T) { + if b := Batch(); b != nil { + t.Fatalf("expected nil, got %+v", b) + } + }) + t.Run("single cmd", func(t *testing.T) { + b := Batch(Quit)() + if l := len(b.(batchMsg)); l != 1 { + t.Fatalf("expected a []Cmd with len 1, got %d", l) + } + }) + t.Run("mixed nil cmds", func(t *testing.T) { + b := Batch(nil, Quit, nil, Quit, nil, nil)() + if l := len(b.(batchMsg)); l != 2 { + t.Fatalf("expected a []Cmd with len 2, got %d", l) + } + }) +} diff --git a/tea.go b/tea.go index fdf29ee650..ee1bd926d1 100644 --- a/tea.go +++ b/tea.go @@ -119,11 +119,18 @@ type Program struct { // } // func Batch(cmds ...Cmd) Cmd { - if len(cmds) == 0 { + var validCmds []Cmd + for _, c := range cmds { + if c == nil { + continue + } + validCmds = append(validCmds, c) + } + if len(validCmds) == 0 { return nil } return func() Msg { - return batchMsg(cmds) + return batchMsg(validCmds) } }