Skip to content

Commit

Permalink
Implement interval.Interval.String()
Browse files Browse the repository at this point in the history
  • Loading branch information
jingyuanliang committed Oct 11, 2024
1 parent 00206de commit cba214a
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/interval/interval.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ func (i Interval) Size() int {
return max(0, i.Last-i.First+1)
}

func (i Interval) String() string {
if i.First < 0 || i.Last < i.First {
return ""
}
if i.First == i.Last {
return strconv.Itoa(i.First)
}
return fmt.Sprintf("%d-%d", i.First, i.Last)
}

func ParseInterval(s string) (Interval, error) {
var i Interval

Expand Down
63 changes: 63 additions & 0 deletions pkg/interval/interval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,69 @@ func TestIntervalSize(t *testing.T) {
}
}

func TestIntervalString(t *testing.T) {
for _, tc := range []struct {
name string
interval Interval
want string
}{
{
name: "standard",
interval: Interval{
First: 42,
Last: 44,
},
want: "42-44",
},
{
name: "single",
interval: Interval{
First: 42,
Last: 42,
},
want: "42",
},
{
name: "zero",
interval: Interval{
First: 0,
Last: 0,
},
want: "0",
},
{
name: "zero-range",
interval: Interval{
First: 0,
Last: 42,
},
want: "0-42",
},
{
name: "negative",
interval: Interval{
First: -1,
Last: 1,
},
want: "",
},
{
name: "reverse",
interval: Interval{
First: 44,
Last: 42,
},
want: "",
},
} {
t.Run(tc.name, func(t *testing.T) {
if got := tc.interval.String(); got != tc.want {
t.Errorf("String = %q, want %q", got, tc.want)
}
})
}
}

func TestParseInterval(t *testing.T) {
for _, tc := range []struct {
name string
Expand Down

0 comments on commit cba214a

Please sign in to comment.