1.0.0 • Published 3 years ago

ttl-buffer v1.0.0

Weekly downloads
3
License
ISC
Repository
github
Last release
3 years ago

ttl-buffer ⌛️

ttl-buffer is a data structure that represents a series of values, which can be map-reduced to a result, each having a time to live (TTL), after which they are removed again. Like roll-reduce, but time-based.

npm version build status dev dependency status ISC-licensed support me via GitHub Sponsors chat with me on Twitter

Installing

npm install ttl-buffer

Example

const ttlBuffer = require('ttl-buffer')

const sumOfLastSecond = ttlBuffer({
	ttl:          1000, // time in milliseconds
	initialValue: 0,
	// This function will be called once you `push` a value.
	in:           (before, entry) => before + entry,
	// This function will be called once a value's TTL is over.
	out:          (before, entry) => before - entry
})

sumOfLastSecond.push(1).push(2)
sumOfLastSecond.valueOf() // -> 3

// 500ms later
sumOfLastSecond.push(3)
sumOfLastSecond.valueOf() // -> 6

// 600ms later, TTL of `1` and `2` is over
sumOfLastSecond.valueOf() // -> 3

// 500ms later, TTL of `3` is over
sumOfLastSecond.valueOf() // -> 0

Contributing

If you have a question, found a bug or want to propose a feature, have a look at the issues page.