Skip to content

Instantly share code, notes, and snippets.

@emilbayes
Created November 18, 2012 18:26
Show Gist options
  • Save emilbayes/4106657 to your computer and use it in GitHub Desktop.
Save emilbayes/4106657 to your computer and use it in GitHub Desktop.
Timed Hash Table
class TimedHashTable
table: {}
timers: {}
size: 0
constructor: (@defaultTimeout) ->
get: (hash) ->
@table[hash]
set: (hash, value, timeout = @defaultTimeout) ->
if not @contains hash
++@size
else
clearTimeout @timers[hash]
@table[hash] = value
@timers[hash] = setTimeout @remove, timeout, hash
@
contains: (hash) ->
@table[hash]?
size: ->
@size
remove: (hash) =>
if @contains hash
clearTimeout @timers[hash]
delete @table[hash]
delete @timers[hash]
--@size
@
purge: ->
clearTimeout(timeout) for timeout of @timers
delete @table
delete @timers
delete @size
@table = {}
@timers = {}
@size = 0
@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment