Skip to content

Commit

Permalink
Add Rate.msSinceLastEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
mceachen committed Feb 26, 2022
1 parent cf5e955 commit cc9bd3e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Rate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,24 @@ describe("Rate", () => {
expectRate(r, 0)
tk.freeze(now + minuteMs)
expectRate(r, 0)
expect(r.msSinceLastEvent).to.eql(minuteMs)
})

it("decays the rate as time elapses", () => {
expectRate(r, 0)
r.onEvent()
expectRate(r, 0)
tk.freeze(now + 10)
expect(r.msSinceLastEvent).to.eql(10)
r.onEvent()
expectRate(r, 1 / 10)
tk.freeze(now + secondMs)
expectRate(r, 2 / secondMs)
tk.freeze(now + 2 * secondMs)
tk.freeze(now + 2 * secondMs + 10)
expect(r.msSinceLastEvent).to.eql(2 * secondMs)
expectRate(r, 1 / secondMs)
tk.freeze(now + minuteMs)
tk.freeze(now + minuteMs + 10)
expect(r.msSinceLastEvent).to.eql(minuteMs)
expectRate(r, 2 / minuteMs)
})

Expand Down
4 changes: 4 additions & 0 deletions src/Rate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export class Rate {
return this.#eventCount
}

get msSinceLastEvent(): number | null {
return this.#lastEventTs == null ? null : Date.now() - this.#lastEventTs
}

get msPerEvent(): number | null {
if (this.#weightedTotalAvg == null || this.#lastEventTs == null) return null
// If we haven't seen an event for a while, include that in the estimate:
Expand Down

0 comments on commit cc9bd3e

Please sign in to comment.