Skip to content

Commit dd071dd

Browse files
Add last-lap exercise
1 parent 9210b05 commit dd071dd

File tree

2 files changed

+381
-44
lines changed

2 files changed

+381
-44
lines changed
Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,57 @@
11
public enum StopwatchState
22
{
3-
Ready,
4-
Running,
5-
Paused,
6-
Stopped
3+
Stopped,
4+
Started
75
}
86

97
public class SplitSecondStopwatch(TimeProvider time)
108
{
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);
1219

1320
public void Start()
1421
{
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;
1627
}
1728

1829
public void Stop()
1930
{
20-
throw new NotImplementedException();
21-
}
31+
if (State != StopwatchState.Started)
32+
throw new InvalidOperationException("Can't stop a stopwatch that is not started.");
2233

23-
public void Split()
34+
_splits.Add(CurrentSplit);
35+
_splitStart = null;
36+
State = StopwatchState.Stopped;
37+
}
38+
39+
public void Reset()
2440
{
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;
2647
}
27-
28-
public void Pause()
48+
49+
public void Lap()
2950
{
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();
3156
}
3257
}

0 commit comments

Comments
 (0)