Created
October 4, 2016 00:51
-
-
Save doug-wade/e8be682366268a2ebd9f093921fffec4 to your computer and use it in GitHub Desktop.
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
const backingObject = Symbol(); | |
const prune = Symbol(); | |
const FIVE_MINUTES = 1000 * 60 * 5; | |
function getTimestamp() { | |
return (new Date()).getTime(); | |
} | |
// Example usage: | |
// const inst = new SimpleReporting(); | |
// inst.record(0); | |
// inst.record(3); | |
// console.log(inst.mean()) // return 1.5 | |
class SimpleReporting { | |
constructor() { | |
this[backingObject] = {}; | |
} | |
record(val) { | |
if (typeof val !== 'number') { | |
throw new Error(`${val} is not a number!`); | |
} | |
const timestamp = getTimestamp(); | |
this[prune](timestamp) | |
if (this[backingObject][timestamp]) { | |
this[backingObject][timestamp].push(val); | |
} else { | |
this[backingObject][timestamp] = [val]; | |
} | |
} | |
mean() { | |
this[prune](getTimestamp()); | |
let num = 0; | |
let denom = 0; | |
Object.keys(this[backingObject]).forEach(key => { | |
num += this[backingObject][key].reduce((prev, curr) => { | |
denom += 1; | |
return prev + curr; | |
}, 0); | |
}); | |
return (num / denom); | |
} | |
[prune](timestamp) { | |
// TODO: currently, memory is more than twice the size of the data, but that may not always | |
// be the case -- someday, we should prune in place. | |
// TODO: We prune when we may not need to -- check to see if there are too many keys before | |
// pruning, and guard in mean. | |
const newBackingObj = {}; | |
Object.keys(this[backingObject]).forEach(key => { | |
if (key >= (timestamp - FIVE_MINUTES)) { | |
newBackingObj[key] = this[backingObject][key]; | |
} | |
}); | |
this[backingObject] = newBackingObj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment