I've encountered this problem and still trying to solve this problem:
You want to log the number of hits to a site.
Implement two functions, log_hit() which gets called when a hit is registered, and get_hits_in_last_five_minutes() which returns the total number of hits in the last five minutes. Assume that all timestamps come in increasing order.
My idea (attempt to solve the problem):
Datastructure: Array.
My Logic:
When log_hit() is called, we basically store the time in ms (Date().getTime() in ms) in the array and store the hits on the particular second in hashmap.
function Counter() {
this.map = {};
this.store = [];
}
Counter.prototype.log_hit = function() {
const d = new Date().getTime()/1000;
this.store.push(d);
this.map[d] = this.map[d] ? this.map[d]++ : 1;
}
Counter.prototype.get_hits_in_last_five_minutes = function() {
const fiveMin = 60 * 60; //seconds.
const initalPointer = new Date().getTime() / 1000 - fiveMin;
// Somehow retrieve the value and return it back
}
However, I don't think this is the most optimal way of solving it , if I wanted to extend the solution for hour or some other granularity.
How would I solve this kind of problem?