UNPKG

1.08 kBJavaScriptView Raw
1/*
2 * @Filename: cacher.js
3 * @Author: jin5354
4 * @Email: xiaoyanjinx@gmail.com
5 * @Last Modified time: 2017-06-23 14:49:53
6 */
7
8export class Cacher {
9
10 constructor(option) {
11 this.cacheMap = new Map()
12 this.option = option
13 this.maxCacheSize = option.maxCacheSize
14 this.ttl = option.ttl
15 this.filters = []
16 }
17
18 addFilter(reg) {
19 this.filters.push(reg)
20 }
21
22 removeFilter(reg) {
23 let index = this.filters.indexOf(reg)
24 if(index !== -1) {
25 this.filters.splice(index, 1)
26 }
27 }
28
29 setCache(key, value) {
30 this.cacheMap.set(JSON.stringify(key), value)
31 if(this.maxCacheSize && this.cacheMap.size > this.maxCacheSize) {
32 this.cacheMap.delete([...(this.cacheMap).keys()][0])
33 }
34 if(this.ttl) {
35 setTimeout(() => {
36 this.cacheMap.delete(key)
37 }, this.ttl)
38 }
39 }
40
41 needCache(key) {
42 return this.filters.some(reg => {
43 return reg.test(key.url)
44 })
45 }
46
47 hasCache(key) {
48 return this.cacheMap.has(JSON.stringify(key))
49 }
50
51 getCache(key) {
52 return this.cacheMap.get(JSON.stringify(key))
53 }
54
55}