Skip to content

Commit

Permalink
ProgressTrack: enforce upper/lower bound when using advancement metho…
Browse files Browse the repository at this point in the history
…ds (#77)

Fixes #64
  • Loading branch information
cwegrzyn authored May 23, 2024
1 parent 930ca1a commit e30793b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
4 changes: 4 additions & 0 deletions src/tracks/progress.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ describe("ProgressTrack", () => {
expect(track.advancedByTicks(10)).toBe(track);
});

it("won't advance negatively below 0 ticks", () => {
expect(make({ progress: 1 }).advancedByTicks(-2).progress).toBe(0);
});

it("won't advance past 40 ticks", () => {
expect(make({ progress: 39 }).advancedByTicks(2).progress).toBe(40);
});
Expand Down
16 changes: 7 additions & 9 deletions src/tracks/progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,26 +164,24 @@ export class ProgressTrack {
return Math.ceil(this.ticksRemaining / this.ticksPerStep);
}

/** Set the meter directly to a specific number of ticks, ensuring legal range for this meter. */
withTicks(ticks: number): ProgressTrack {
const newProgress = Math.min(
this.unbounded ? Number.MAX_SAFE_INTEGER : MAX_TICKS,
ticks,
const newProgress = Math.max(
0,
Math.min(this.unbounded ? Number.MAX_SAFE_INTEGER : MAX_TICKS, ticks),
);
if (this.complete || newProgress === this.progress) return this;
return new ProgressTrack({ ...this, progress: newProgress });
}

/** Advance the meter by `steps`, ensuring legal range for this meter. */
advanced(steps: number): ProgressTrack {
return this.advancedByTicks(steps * this.ticksPerStep);
}

/** Advance the meter by `ticks`, ensuring legal range for this meter. */
advancedByTicks(ticks: number): ProgressTrack {
const newProgress = Math.min(
this.unbounded ? Number.MAX_SAFE_INTEGER : MAX_TICKS,
this.progress + ticks,
);
if (this.complete || newProgress === this.progress) return this;
return new ProgressTrack({ ...this, progress: newProgress });
return this.withTicks(this.progress + ticks);
}

completed(): ProgressTrack {
Expand Down

0 comments on commit e30793b

Please sign in to comment.