-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathcache.js
41 lines (33 loc) · 1.41 KB
/
cache.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
var assert = require('assert')
var LRU = require('nanolru')
module.exports = ChooComponentCache
function ChooComponentCache (state, emit, lru) {
assert.ok(this instanceof ChooComponentCache, 'ChooComponentCache should be created with `new`')
assert.equal(typeof state, 'object', 'ChooComponentCache: state should be type object')
assert.equal(typeof emit, 'function', 'ChooComponentCache: emit should be type function')
if (typeof lru === 'number') this.cache = new LRU(lru)
else this.cache = lru || new LRU(100)
this.state = state
this.emit = emit
}
// Get & create component instances.
ChooComponentCache.prototype.render = function (Component, id) {
assert.equal(typeof Component, 'function', 'ChooComponentCache.render: Component should be type function')
assert.ok(typeof id === 'string' || typeof id === 'number', 'ChooComponentCache.render: id should be type string or type number')
var el = this.cache.get(id)
if (!el) {
var args = []
for (var i = 2, len = arguments.length; i < len; i++) {
args.push(arguments[i])
}
args.unshift(Component, id, this.state, this.emit)
el = newCall.apply(newCall, args)
this.cache.set(id, el)
}
return el
}
// Because you can't call `new` and `.apply()` at the same time. This is a mad
// hack, but hey it works so we gonna go for it. Whoop.
function newCall (Cls) {
return new (Cls.bind.apply(Cls, arguments)) // eslint-disable-line
}