-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (29 loc) · 874 Bytes
/
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
function Memorize (config) {
let time = config.time ? config.time : 100000
return function (target, name, descriptor) {
let caches = {}
let fn = descriptor.value
if (typeof fn !== 'function') {
console.error('Memorize decorator can only decorate a function!')
}
descriptor.value = function () {
let currentTime = Date.now()
let arg = arguments[0], option = arguments[1]
if (option === 'delete') {
delete caches[arg]
}
let key = JSON.stringify(arg)
let cache = caches[key]
// 若存在缓存并且没有过期,直接返回缓存的值
if (cache && currentTime < cache.expired) {
return cache.value
} else {
let value = fn.apply(this, [arg])
caches[key] = { value, expired: Date.now() + time }
return value
}
}
return descriptor
}
}
module.exports = Memorize