Code coverage report for ttl/index.js

Statements: 100% (41 / 41)      Branches: 100% (20 / 20)      Functions: 100% (10 / 10)      Lines: 100% (41 / 41)      Ignored: none     

All files » ttl/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 801 1   1 9   9 9     1   1 12 3     9   9   9       5       9     1 9   9 6 2 2 2   4     3     9     1 18 9   9 9 9   9       1 1 1       1 2 2       1 15     1  
var util = require('util');
var events = require('events');
 
function Cache(opts) {
  opts = opts || {};
 
  this._store = {};
  this._ttl = Number(opts.ttl);
}
 
util.inherits(Cache, events.EventEmitter);
 
Cache.prototype.put = function (key, val, ttl) {
  if (key === undefined || val === undefined) {
    return;
  }
 
  ttl = ttl === undefined ? this._ttl : Number(ttl);
 
  this.del(key);
 
  this._store[key] = {
    val: val,
    expire: now() + ttl,
    timeout: setTimeout(function() {
      this.del(key);
    }.bind(this), ttl)
  };
 
  this.emit('put', key, val, ttl);
};
 
Cache.prototype.get = function (key) {
  var rec = this._store[key];
 
  if (rec) {
    if (!(rec.expire && rec.expire > now())) {
      this.del(key);
      this.emit('miss', key);
      rec = undefined;
    } else {
      this.emit('hit', key, rec.val);
    }
  } else {
    this.emit('miss', key);
  }
 
  return rec && rec.val;
};
 
Cache.prototype.del = function (key) {
  if (this._store[key]) {
    var val = this._store[key].val;
 
    clearTimeout(this._store[key].timeout);
    delete this._store[key];
    this.emit('del', key, val);
 
    return val;
  }
};
 
Cache.prototype.clear = function () {
  Object.keys(this._store).forEach(function(key) {
    this.del(key);
  }.bind(this));
};
 
Cache.prototype.size = function () {
  return Object.keys(this._store).reduce(function(size, key) {
    return size + (this.get(key) !== undefined ? 1 : 0);
  }.bind(this), 0);
};
 
function now() {
  return Date.now();
}
 
module.exports = Cache;