1 |
|
2 | /*!
|
3 | * Connect - Cache
|
4 | * Copyright(c) 2011 Sencha Inc.
|
5 | * MIT Licensed
|
6 | */
|
7 |
|
8 | /**
|
9 | * Expose `Cache`.
|
10 | */
|
11 |
|
12 | module.exports = Cache;
|
13 |
|
14 | /**
|
15 | * LRU cache store.
|
16 | *
|
17 | * @param {Number} limit
|
18 | * @api private
|
19 | */
|
20 |
|
21 | function Cache(limit) {
|
22 | this.store = {};
|
23 | this.keys = [];
|
24 | this.limit = limit;
|
25 | }
|
26 |
|
27 | /**
|
28 | * Touch `key`, promoting the object.
|
29 | *
|
30 | * @param {String} key
|
31 | * @param {Number} i
|
32 | * @api private
|
33 | */
|
34 |
|
35 | Cache.prototype.touch = function(key, i){
|
36 | this.keys.splice(i,1);
|
37 | this.keys.push(key);
|
38 | };
|
39 |
|
40 | /**
|
41 | * Remove `key`.
|
42 | *
|
43 | * @param {String} key
|
44 | * @api private
|
45 | */
|
46 |
|
47 | Cache.prototype.remove = function(key){
|
48 | delete this.store[key];
|
49 | };
|
50 |
|
51 | /**
|
52 | * Get the object stored for `key`.
|
53 | *
|
54 | * @param {String} key
|
55 | * @return {Array}
|
56 | * @api private
|
57 | */
|
58 |
|
59 | Cache.prototype.get = function(key){
|
60 | return this.store[key];
|
61 | };
|
62 |
|
63 | /**
|
64 | * Add a cache `key`.
|
65 | *
|
66 | * @param {String} key
|
67 | * @return {Array}
|
68 | * @api private
|
69 | */
|
70 |
|
71 | Cache.prototype.add = function(key){
|
72 | // initialize store
|
73 | var len = this.keys.push(key);
|
74 |
|
75 | // limit reached, invalid LRU
|
76 | if (len > this.limit) this.remove(this.keys.shift());
|
77 |
|
78 | var arr = this.store[key] = [];
|
79 | arr.createdAt = new Date;
|
80 | return arr;
|
81 | };
|