JSFiddle - React, Tailwind, and code Playground

by Nishchal Joshi

JavaScript

//Log hit count
/*

# this gets called every time my site gets a hit
log_hit()
# I get to call this anytime I want.
# returns number of hits in the last 5 minutes.
get_hits()

*/

var lastMinutes = 5;
var lastMinutesInMilli = lastMinutes*60*1000;

function hits(){
  //Store hits in this object for better performance
  var that = this;
  //totalCount will keep track of how many times our site was hit
  //It will help us get efficiency of O(1)
  this.hitStore = { "totalCount" : 0};
  this.startPointer = null;
  //this.clean_hits = null;
  //This inverval will delete older properties from hitStore object
  //and decrement hitStore["totalCount"] by the old properties right before deleting them
  this.cleanHitsInterval = setInterval(function(){if(that.clean_hits != null){that.clean_hits()}}, 1);
}

//This method is used to log hits each time it is called
//It will find if a hit was added in current milliseconds
//If it was then increment the counter
//If not then create a new entry and add value 1 to it
//It will also increment our counter hitStore["totalCount"] each time
hits.prototype.log_hit = function(){
  var now = Date.now();
  if(!this.startPointer || || this.hitStore["totalCount"] == 0){
    this.startPointer = now;
  }
  if(this.hitStore[now]){
    this.hitStore[now] += 1;
  }else{
    this.hitStore[now] = 1;
  }
  this.hitStore["totalCount"] ++;
}

//This function will do a very important job updating //hitStore["totalCount"] and removing old counter From hitStore object

//We need to start from startPointer and go until now - (5 minutes -> milli Seconds) and remove all the elements and decrement their counter values from hitStore["totalCount"] right before.
hits.prototype.clean_hits = function(){
//If startPointer is not defined then we do not have any element to remove from hitStore object
  if(this.startPointer == null || this.hitStore["totalCount"] == 0){
  	return;
  }
  console.log("this.startPointer: " + this.startPointer);
  console.log("total Count:...