@@ -2,31 +2,67 @@ public enum StopwatchState
22{
33 Ready ,
44 Running ,
5- Paused ,
6- Stopped
5+ Paused
76}
87
98public class SplitSecondStopwatch ( TimeProvider time )
109{
10+ private readonly List < TimeSpan > _previousLapSegments = new ( ) ;
11+ private DateTimeOffset ? _currentSegmentStart ;
12+
1113 public StopwatchState State { get ; private set ; }
1214
15+ public List < TimeSpan > PreviousLaps { get ; } = new ( ) ;
16+
17+ public TimeSpan CurrentLap => PreviousLapSegments + CurrentSegment ;
18+
19+ private TimeSpan PreviousLapSegments => _previousLapSegments . Aggregate ( TimeSpan . Zero , ( total , segment ) => total + segment ) ;
20+
21+ private TimeSpan CurrentSegment => _currentSegmentStart is { } start ? time . GetUtcNow ( ) - start : TimeSpan . Zero ;
22+
1323 public void Start ( )
1424 {
15- throw new NotImplementedException ( ) ;
25+ if ( State == StopwatchState . Paused )
26+ _currentSegmentStart = null ;
27+ else if ( State == StopwatchState . Running )
28+ throw new InvalidOperationException ( ) ;
29+
30+ _currentSegmentStart ??= time . GetUtcNow ( ) ;
31+
32+ State = StopwatchState . Running ;
1633 }
1734
1835 public void Stop ( )
1936 {
20- throw new NotImplementedException ( ) ;
37+ if ( State == StopwatchState . Ready )
38+ return ;
39+
40+ PreviousLaps . Add ( CurrentLap ) ;
41+ _currentSegmentStart = null ;
42+ State = StopwatchState . Ready ;
2143 }
2244
2345 public void Split ( )
2446 {
25- throw new NotImplementedException ( ) ;
47+ AddSegment ( ) ;
2648 }
2749
2850 public void Pause ( )
2951 {
30- throw new NotImplementedException ( ) ;
52+ State = StopwatchState . Paused ;
53+ AddSegment ( ) ;
54+ }
55+
56+ public void Reset ( )
57+ {
58+ Stop ( ) ;
59+ _previousLapSegments . Clear ( ) ;
60+ Start ( ) ;
61+ }
62+
63+ private void AddSegment ( )
64+ {
65+ _previousLapSegments . Add ( CurrentSegment ) ;
66+ _currentSegmentStart = null ;
3167 }
3268}
0 commit comments