|
1 | 1 | public enum StopwatchState |
2 | 2 | { |
3 | | - Ready, |
4 | | - Running, |
5 | | - Paused, |
6 | | - Stopped |
| 3 | + Stopped, |
| 4 | + Started |
7 | 5 | } |
8 | 6 |
|
9 | 7 | public class SplitSecondStopwatch(TimeProvider time) |
10 | 8 | { |
11 | | - public StopwatchState State { get; private set; } |
| 9 | + private readonly List<TimeSpan> _splits = new(); |
| 10 | + private DateTimeOffset? _splitStart; |
| 11 | + |
| 12 | + private TimeSpan PreviousSplits => _splits.Aggregate(TimeSpan.Zero, (total, split) => total + split); |
| 13 | + private TimeSpan CurrentSplit => _splitStart is {} start ? time.GetUtcNow() - start : TimeSpan.Zero; |
| 14 | + |
| 15 | + public StopwatchState State { get; private set; } = StopwatchState.Stopped; |
| 16 | + public List<TimeSpan> Laps { get; } = []; |
| 17 | + public TimeSpan Split => CurrentSplit + PreviousSplits; |
| 18 | + public TimeSpan Total => Split + Laps.Aggregate(TimeSpan.Zero, (total, split) => total + split); |
12 | 19 |
|
13 | 20 | public void Start() |
14 | 21 | { |
15 | | - throw new NotImplementedException(); |
| 22 | + if (State != StopwatchState.Stopped) |
| 23 | + throw new InvalidOperationException("Can't start a stopwatch that is not stopped."); |
| 24 | + |
| 25 | + _splitStart = time.GetUtcNow(); |
| 26 | + State = StopwatchState.Started; |
16 | 27 | } |
17 | 28 |
|
18 | 29 | public void Stop() |
19 | 30 | { |
20 | | - throw new NotImplementedException(); |
21 | | - } |
| 31 | + if (State != StopwatchState.Started) |
| 32 | + throw new InvalidOperationException("Can't stop a stopwatch that is not started."); |
22 | 33 |
|
23 | | - public void Split() |
| 34 | + _splits.Add(CurrentSplit); |
| 35 | + _splitStart = null; |
| 36 | + State = StopwatchState.Stopped; |
| 37 | + } |
| 38 | + |
| 39 | + public void Reset() |
24 | 40 | { |
25 | | - throw new NotImplementedException(); |
| 41 | + if (State != StopwatchState.Stopped) |
| 42 | + throw new InvalidOperationException("Can't reset a stopwatch that is not stopped."); |
| 43 | + |
| 44 | + _splits.Clear(); |
| 45 | + _splitStart = null; |
| 46 | + State = StopwatchState.Stopped; |
26 | 47 | } |
27 | | - |
28 | | - public void Pause() |
| 48 | + |
| 49 | + public void Lap() |
29 | 50 | { |
30 | | - throw new NotImplementedException(); |
| 51 | + if (State != StopwatchState.Started) |
| 52 | + throw new InvalidOperationException("Can't lap a stopwatch that is not started stopped."); |
| 53 | + |
| 54 | + _splits.Add(CurrentSplit); |
| 55 | + _splitStart = time.GetUtcNow(); |
31 | 56 | } |
32 | 57 | } |
0 commit comments