Skip to content

Commit

Permalink
refactor: simplify implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane committed Nov 3, 2022
1 parent 0246482 commit 174c711
Showing 1 changed file with 18 additions and 28 deletions.
46 changes: 18 additions & 28 deletions check.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,56 +9,46 @@ import "fmt"

// That checks whether cond is true, and if not, records the error. That panics
// if the error is nil.
func That(cond bool, err error) *check {
return new(check).That(cond, err)
func That(cond bool, err error) *state {
return new(state).That(cond, err)
}

// Thatf checks whether cond is true, and if not, creates an error from format
// and args, then records it.
func Thatf(cond bool, format string, args ...any) *check {
return That(cond, fmt.Errorf(format, args...))
func Thatf(cond bool, format string, args ...any) *state {
return new(state).Thatf(cond, format, args...)
}

// check holds the conditions to check and their corresponding errors.
type check struct {
conds []bool
errs []error
// state holds the errors of the failed conditions.
type state struct {
errs []error
}

// That checks whether cond is true, and if not, records the error. That panics
// if the error is nil.
func (ch *check) That(cond bool, err error) *check {
func (s *state) That(cond bool, err error) *state {
if err == nil {
panic("check: a nil error is provided")
}
ch.conds = append(ch.conds, cond)
ch.errs = append(ch.errs, err)
return ch
if !cond {
s.errs = append(s.errs, err)
}
return s
}

// Thatf checks whether cond is true, and if not, creates an error from format
// and args, then records it.
func (ch *check) Thatf(cond bool, format string, args ...any) *check {
return ch.That(cond, fmt.Errorf(format, args...))
func (s *state) Thatf(cond bool, format string, args ...any) *state {
return s.That(cond, fmt.Errorf(format, args...))
}

// FirstError returns the error of the first failed condition.
func (ch *check) FirstError() error {
for i := range ch.conds {
if !ch.conds[i] {
return ch.errs[i]
}
func (s *state) FirstError() error {
if len(s.errs) > 0 {
return s.errs[0]
}
return nil
}

// AllErrors returns the errors of all failed conditions.
func (ch *check) AllErrors() []error {
var errs []error
for i := range ch.conds {
if !ch.conds[i] {
errs = append(errs, ch.errs[i])
}
}
return errs
}
func (s *state) AllErrors() []error { return s.errs }

0 comments on commit 174c711

Please sign in to comment.