Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added back in my k-v cache.

  • Loading branch information...
commit 36efe46886494ca686d62f334927171a8be16b5c 1 parent 141b37d
J. T. L. ironwallaby authored

Showing 1 changed file with 46 additions and 0 deletions. Show diff stats Hide diff stats

  1. +46 0 index.js
46 index.js
@@ -74,3 +74,49 @@ exports.timeBasedWithGrace = function(func, soft, hard) {
74 74 })
75 75 }
76 76 }
  77 +
  78 +exports.sizeBasedKeyValue = function(func, size) {
  79 + var cache = [],
  80 + callbacks = {}
  81 +
  82 + size += size
  83 +
  84 + return function(key, callback) {
  85 + /* Look up in the cache. */
  86 + var i
  87 +
  88 + for(i = 0; i !== cache.length; i += 2)
  89 + if(cache[i] === key) {
  90 + if(i !== 0)
  91 + Array.prototype.unshift.apply(cache, cache.splice(i, 2))
  92 +
  93 + return callback(null, cache[1])
  94 + }
  95 +
  96 + /* Somebody else is already polling the backend. Get notified when they're
  97 + * done, and bail. */
  98 + if(callbacks[key]) {
  99 + callbacks[key].push(callback)
  100 + return
  101 + }
  102 +
  103 + callbacks[key] = [callback]
  104 +
  105 + /* Call the backing store. */
  106 + return func(key, function(err, value) {
  107 + /* Successful result? Then add it to the cache. */
  108 + if(!err) {
  109 + if(cache.length === size)
  110 + cache.length -= 2
  111 +
  112 + cache.unshift(key, value)
  113 + }
  114 +
  115 + /* Notify all the saved callbacks, and then clean up. */
  116 + while(callbacks[key].length)
  117 + callbacks[key].pop()(err, value)
  118 +
  119 + delete callbacks[key]
  120 + })
  121 + }
  122 +}

0 comments on commit 36efe46

Please sign in to comment.
Something went wrong with that request. Please try again.