Skip to content

Instantly share code, notes, and snippets.

@Raynos

Raynos/purge.js Secret

Last active December 17, 2015 02:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Raynos/3059e454389f819861a9 to your computer and use it in GitHub Desktop.
// create a buffer
var buf = []
buf.push({ timestamp: Date.now(), value: whatever })
setInterval(function () {
purge(buf, 120 * 1000)
}, 1000)
function purge(buffer, timeToLive) {
var now = Date.now()
// while the first item in the buffer is too old
// remove the head of the buffer.
// terminates when the tail of the buffer is recent
// this works because buffer is sorted chronologically
while (buffer[0] && buffer[0].timestamp < now - timeToLive) {
buffer.shift()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment