diff options
| author | Stephen Blott | 2015-05-02 08:30:15 +0100 | 
|---|---|---|
| committer | Stephen Blott | 2015-05-02 14:35:49 +0100 | 
| commit | d848f50fb1c199de581bf63e18495b7f4d0c4faf (patch) | |
| tree | a1f6c3cd24bcc8da721002b215d06ba6c9528a1b /lib/utils.coffee | |
| parent | 3616e0d01ffb38e9b7d344b99ad6ce7bc6aa071e (diff) | |
| download | vimium-d848f50fb1c199de581bf63e18495b7f4d0c4faf.tar.bz2 | |
Search completion; refactor to separate file.
Diffstat (limited to 'lib/utils.coffee')
| -rw-r--r-- | lib/utils.coffee | 38 | 
1 files changed, 38 insertions, 0 deletions
| diff --git a/lib/utils.coffee b/lib/utils.coffee index fba03b61..338e535d 100644 --- a/lib/utils.coffee +++ b/lib/utils.coffee @@ -194,5 +194,43 @@ globalRoot.extend = (hash1, hash2) ->      hash1[key] = hash2[key]    hash1 +# A simple cache. Entries used within an expiry period are retained (for one more expiry period), otherwise +# they are discarded. +class SimpleCache +  # expiry: expiry time in milliseconds (default, one hour) +  # entries: maximum number of entries +  constructor: (@expiry = 60 * 60 * 1000, @entries = 1000) -> +    @cache = {} +    @previous = {} +    setInterval (=> @rotate()), @expiry + +  rotate: -> +    @previous = @cache +    @cache = {} + +  has: (key) -> +    (key of @cache) or key of @previous + +  get: (key) -> +    console.log "get", key +    if key of @cache +      @cache[key] +    else if key of @previous +      @cache[key] = @previous[key] +    else +      null + +  # Set value, and return that value.  If value is null, then delete key. +  set: (key, value = null) -> +    if value? +      @cache[key] = value +      delete @previous[key] +      @rotate() if @entries < Object.keys(@cache).length +    else +      delete @cache[key] +      delete @previous[key] +    value +  root = exports ? window  root.Utils = Utils +root.SimpleCache = SimpleCache | 
