]>
Commit | Line | Data |
---|---|---|
6527f429 DM |
1 | /**\r |
2 | * Limited cache is a size limited cache container that stores limited number of objects.\r | |
3 | * \r | |
4 | * When {@link #get} is called, the container will try to find the object in the list.\r | |
5 | * If failed it will call the {@link #feeder} to create that object. If there are too many\r | |
6 | * objects in the container, the old ones are removed.\r | |
7 | * \r | |
8 | * __Note:__ This is not using a Least Recently Used policy due to simplicity and performance consideration.\r | |
9 | * @private\r | |
10 | */\r | |
11 | Ext.define('Ext.draw.LimitedCache', {\r | |
12 | \r | |
13 | config: {\r | |
14 | /**\r | |
15 | * @cfg {Number}\r | |
16 | * The amount limit of the cache.\r | |
17 | */\r | |
18 | limit: 40,\r | |
19 | \r | |
20 | /**\r | |
21 | * @cfg {Function}\r | |
22 | * Function that generates the object when look-up failed.\r | |
23 | * @return {Number}\r | |
24 | */\r | |
25 | feeder: function () {\r | |
26 | return 0;\r | |
27 | },\r | |
28 | \r | |
29 | /**\r | |
30 | * @cfg {Object}\r | |
31 | * The scope for {@link #feeder}\r | |
32 | */\r | |
33 | scope: null\r | |
34 | },\r | |
35 | \r | |
36 | cache: null,\r | |
37 | \r | |
38 | constructor: function (config) {\r | |
39 | this.cache = {};\r | |
40 | this.cache.list = [];\r | |
41 | this.cache.tail = 0;\r | |
42 | this.initConfig(config);\r | |
43 | },\r | |
44 | \r | |
45 | /**\r | |
46 | * Get a cached object.\r | |
47 | * @param {String} id\r | |
48 | * @param {Mixed...} args Arguments appended to feeder.\r | |
49 | * @return {Object}\r | |
50 | */\r | |
51 | get: function (id) {\r | |
52 | // TODO: Implement cache hit optimization\r | |
53 | var cache = this.cache,\r | |
54 | limit = this.getLimit(),\r | |
55 | feeder = this.getFeeder(),\r | |
56 | scope = this.getScope() || this;\r | |
57 | \r | |
58 | if (cache[id]) {\r | |
59 | return cache[id].value;\r | |
60 | }\r | |
61 | if (cache.list[cache.tail]) {\r | |
62 | delete cache[cache.list[cache.tail].cacheId];\r | |
63 | }\r | |
64 | cache[id] = cache.list[cache.tail] = {\r | |
65 | value: feeder.apply(scope, Array.prototype.slice.call(arguments, 1)),\r | |
66 | cacheId: id\r | |
67 | };\r | |
68 | cache.tail++;\r | |
69 | if (cache.tail === limit) {\r | |
70 | cache.tail = 0;\r | |
71 | }\r | |
72 | return cache[id].value;\r | |
73 | },\r | |
74 | \r | |
75 | /**\r | |
76 | * Clear all the objects.\r | |
77 | */\r | |
78 | clear: function () {\r | |
79 | this.cache = {};\r | |
80 | this.cache.list = [];\r | |
81 | this.cache.tail = 0;\r | |
82 | }\r | |
83 | });\r |