Created
July 27, 2017 21:49
-
-
Save lynnagara/d0cf94fd91bd9e5922f4b22f97b7d941 to your computer and use it in GitHub Desktop.
Counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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