Skip to content

Commit

Permalink
implement the stringer interface
Browse files Browse the repository at this point in the history
  • Loading branch information
sosodev committed May 29, 2022
1 parent cb2cd96 commit eb820b1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
24 changes: 16 additions & 8 deletions duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import (

// Duration holds all the smaller units that make up the duration
type Duration struct {
Years float64
Months float64
Weeks float64
Days float64
Hours float64
Minutes float64
Seconds float64
originalString string
Years float64
Months float64
Weeks float64
Days float64
Hours float64
Minutes float64
Seconds float64
}

const (
Expand All @@ -33,7 +34,9 @@ var (
// if parsing fails an error is returned instead
func Parse(d string) (*Duration, error) {
state := parsingPeriod
duration := &Duration{}
duration := &Duration{
originalString: d,
}
num := ""
var err error

Expand Down Expand Up @@ -137,3 +140,8 @@ func (duration *Duration) ToTimeDuration() time.Duration {

return timeDuration
}

// String returns the duration string from which the *Duration was parsed
func (duration *Duration) String() string {
return duration.originalString
}
30 changes: 22 additions & 8 deletions duration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,31 @@ func TestParse(t *testing.T) {
name: "period-only",
args: args{d: "P4Y"},
want: &Duration{
Years: 4,
originalString: "P4Y",
Years: 4,
},
wantErr: false,
},
{
name: "time-only-decimal",
args: args{d: "T2.5S"},
want: &Duration{
Seconds: 2.5,
originalString: "T2.5S",
Seconds: 2.5,
},
wantErr: false,
},
{
name: "full",
args: args{d: "P3Y6M4DT12H30M5.5S"},
want: &Duration{
Years: 3,
Months: 6,
Days: 4,
Hours: 12,
Minutes: 30,
Seconds: 5.5,
originalString: "P3Y6M4DT12H30M5.5S",
Years: 3,
Months: 6,
Days: 4,
Hours: 12,
Minutes: 30,
Seconds: 5.5,
},
wantErr: false,
},
Expand Down Expand Up @@ -130,3 +133,14 @@ func TestDuration_ToTimeDuration(t *testing.T) {
})
}
}

func TestDuration_String(t *testing.T) {
duration, err := Parse("P3Y6M4DT12H30M5.5S")
if err != nil {
t.Fatal(err)
}

if duration.String() != "P3Y6M4DT12H30M5.5S" {
t.Errorf("expected: %s, got: %s", "P3Y6M4DT12H30M5.5S", duration.String())
}
}

0 comments on commit eb820b1

Please sign in to comment.