Skip to content

Commit a8777fa

Browse files
committed
Add method IsValid to type Interval
1 parent 7c006e8 commit a8777fa

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

intervalset.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ func (r Interval[E]) Equal(r2 Interval[E]) bool {
4444
return r.Low.Compare(r2.Low) == 0 && r.High.Compare(r2.High) == 0
4545
}
4646

47+
// IsValid reports whether r is a valid Interval.
48+
// A valid Interval r either satisfies r.Low.Compare(r.High) < 0 or equals to
49+
// the zero value.
50+
func (r Interval[E]) IsValid() bool {
51+
c := r.Low.Compare(r.High)
52+
return c < 0 || c == 0 && r.Equal(Interval[E]{})
53+
}
54+
4755
// Set returns the set of elements that are in r.
4856
// If r is the zero value, Set returns an empty set.
4957
// If r is an invalid Interval, Set panics.

intervalset_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,25 @@ import (
77
"github.com/b97tsk/intervals/elems"
88
)
99

10+
func TestIsValid(t *testing.T) {
11+
type E = elems.Int
12+
13+
assertions := []bool{
14+
Interval[E]{}.IsValid(),
15+
One[E](0).IsValid(),
16+
Range[E](1, 5).IsValid(),
17+
!Range[E](5, 1).IsValid(),
18+
!Range[E](5, 5).IsValid(),
19+
}
20+
21+
for i, ok := range assertions {
22+
if !ok {
23+
t.Fail()
24+
t.Logf("Case %v: FAILED", i)
25+
}
26+
}
27+
}
28+
1029
func TestCreation(t *testing.T) {
1130
type E = elems.Int
1231

0 commit comments

Comments
 (0)