Skip to content

Instantly share code, notes, and snippets.

@lynnagara
Created July 27, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynnagara/d0cf94fd91bd9e5922f4b22f97b7d941 to your computer and use it in GitHub Desktop.
Save lynnagara/d0cf94fd91bd9e5922f4b22f97b7d941 to your computer and use it in GitHub Desktop.
Counter
function createCounter () {
const hits = {}
return {
record,
total
}
let lastRecordedBucket
setInterval(function () {
// delete
}, 30 * 1000)
function record (timestamp) {
const key = getKey(timestamp)
lastRecordedBucket = key
hits[key] = hits[key] ? hits[key] + 1 : 1
}
function getKey (timestamp) {
return (timestamp - timestamp % 60).toString()
}
function total (min, max) {
return Object.entries(hits).reduce(function (acc, bucket) {
const startTime = parseInt(bucket[0])
const adjustedStartTime = startTime - (startTime % 60)
if (adjustedStartTime >= min && adjustedStartTime + 60 <= max) {
return acc + bucket[1]
} else {
return acc
}
}, 0)
}
}
const myCounter = createCounter()
myCounter.record(200)
myCounter.record(2003)
myCounter.record(2004)
myCounter.record(3000)
myCounter.record(20001)
myCounter.record(2003)
console.log(myCounter.total(200, 3000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment