Skip to content

Commit

Permalink
Add method IsValid to type Interval
Browse files Browse the repository at this point in the history
  • Loading branch information
b97tsk committed Jan 25, 2024
1 parent 7c006e8 commit a8777fa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions intervalset.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ func (r Interval[E]) Equal(r2 Interval[E]) bool {
return r.Low.Compare(r2.Low) == 0 && r.High.Compare(r2.High) == 0
}

// IsValid reports whether r is a valid Interval.
// A valid Interval r either satisfies r.Low.Compare(r.High) < 0 or equals to
// the zero value.
func (r Interval[E]) IsValid() bool {
c := r.Low.Compare(r.High)
return c < 0 || c == 0 && r.Equal(Interval[E]{})
}

// Set returns the set of elements that are in r.
// If r is the zero value, Set returns an empty set.
// If r is an invalid Interval, Set panics.
Expand Down
19 changes: 19 additions & 0 deletions intervalset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,25 @@ import (
"github.com/b97tsk/intervals/elems"
)

func TestIsValid(t *testing.T) {
type E = elems.Int

assertions := []bool{
Interval[E]{}.IsValid(),
One[E](0).IsValid(),
Range[E](1, 5).IsValid(),
!Range[E](5, 1).IsValid(),
!Range[E](5, 5).IsValid(),
}

for i, ok := range assertions {
if !ok {
t.Fail()
t.Logf("Case %v: FAILED", i)
}
}
}

func TestCreation(t *testing.T) {
type E = elems.Int

Expand Down

0 comments on commit a8777fa

Please sign in to comment.