1.0.1 • Published 4 years ago

drophash v1.0.1

Weekly downloads
2
License
ISC
Repository
github
Last release
4 years ago

drophash

This is just a simple object that you can use to insert things into with a key, and then get them back out via the key.

It's special in that if you put something in, it will vanish after a while if you don't take it back out again and trying to get it will just return null.

I used this to store WebSocket messages temporarily. If a reply doesn't materialize for a message within a few seconds, I just toss it.

Node.js

npm install drophash

DropHash = require( "drophash" )

dh = new DropHash();

Browser

<script src="drophash.js">

	dh = new DropHash();

<script>

Usage

dh = new DropHash()

dh.insert( "key", "a thing", 2000 )

// 1 second later

thing = dh.remove( "key" )			// thing == "a thing"

dh.insert( "key", { a: "thing" }, 2000 )

// 3 seconds later ...

thing = dh.remove( "key" )			// thing == null

Changing Default TTL

If you don't provide a TTL when you insert, then the default TTL is 60 seconds.

You can change that default like this:

dh = new DropHash( 10 * 1000 )		// Use 10 second default TTL

insert( "key", "a thing" )		// times out in 10 seconds

Specifying a TTL with insert() will take precedence.

Changing Default Interval

The internal timer checks for things to drop every 10 seconds by default. It only runs when there is something in the hash.

You can change the frequencey of the timer like this:

dh = new DropHash( 30 * 1000, 1 * 1000 )		// Use 1 second interval

// Items are dropped after being in hash for 30 secs or more, and
// the timer checks every second for items to drop.

Caution

Inserting something with a key will overwrite objects already stored under that key:

dh.insert( "key", "a thing" )

dh.insert( "key", "other thing" )		// wipes out "a thing"

thing = dh.remove( "key" )			// thing == "other thing"