JSFiddle - React, Tailwind, and code Playground

by eurica

HTML

<!-- 
Start: 3:04 end 3:28
Notes:
-- I had to google syntax for a new class: https://javascript.info/class
-- google date formats in JS: 
-- typos everywhere: Manth.Floor not floor, I also got the for loop out of order
==>

JavaScript

class HitCounter {
  constructor() {
    this.hitsbyminute = {}
  }
  add() {
    //console.log("add()")
    var minutesSinceEpoch = Math.floor(Date.now() / 1000)
    this.hitsbyminute[minutesSinceEpoch] ?
      this.hitsbyminute[minutesSinceEpoch]++
      :
      this.hitsbyminute[minutesSinceEpoch] = 1
    // TODO: purge old data > 5 minutes ago
  }
  count() {
    console.log("count()")
    //console.log(this.hitsbyminute)
    var minutesSinceEpoch = Math.floor(Date.now() / 1000)
    var totalHits = 0;
    for (var i = 0; i < 5; i++) {
      //console.log(i+": "+(minutesSinceEpoch-i)+ ": " + this.hitsbyminute[minutesSinceEpoch - i])
      if (this.hitsbyminute[minutesSinceEpoch - i]) totalHits += this.hitsbyminute[minutesSinceEpoch - i]
    }
    //console.log(totalHits)
    return totalHits;
  }
}

webCounter = new HitCounter();

webCounter.count();
webCounter.add();
webCounter.add();
webCounter.add();
webCounter.add();
webCounter.count();


// TODO: real tests