({
lifetime: defaultLifetime = 3000,
onDispose,
} = {})
| 1 | export default function initCache({ |
| 2 | lifetime: defaultLifetime = 3000, |
| 3 | onDispose, |
| 4 | } = {}) { |
| 5 | let cache = Object.create(null); |
| 6 | // setTimeout call is very expensive when done frequently, |
| 7 | // 1000 calls performed for 50 scripts consume 50ms on each tab load, |
| 8 | // so we'll schedule trim() just once per event loop cycle, |
| 9 | // and then trim() will trim the cache and reschedule itself to the earliest expiry time. |
| 10 | let timer; |
| 11 | let minLifetime = -1; |
| 12 | // same goes for the performance.now() used by hit() and put() which is why we expose batch(true) |
| 13 | // to start an operation that reuses the same value of now(), and batch(false) to end it |
| 14 | let batchStarted; |
| 15 | let batchStartTime; |
| 16 | // eslint-disable-next-line no-return-assign |
| 17 | const getNow = () => batchStarted && batchStartTime || (batchStartTime = performance.now()); |
| 18 | const OVERRUN = 1000; // in ms, to reduce frequency of calling setTimeout |
| 19 | const exports = { |
| 20 | batch, get, some, pop, put, del, has, hit, destroy, |
| 21 | }; |
| 22 | if (process.env.DEV) Object.defineProperty(exports, 'data', { get: () => cache }); |
| 23 | return exports; |
| 24 | function batch(enable) { |
| 25 | batchStarted = enable; |
| 26 | batchStartTime = 0; |
| 27 | } |
| 28 | function get(key, def, shouldHit = true) { |
| 29 | const item = cache[key]; |
| 30 | if (item && shouldHit) { |
| 31 | reschedule(item, item.lifetime); |
| 32 | } |
| 33 | return item ? item.value : def; |
| 34 | } |
| 35 | /** |
| 36 | * @param {(val:?, key:string) => void} fn |
| 37 | * @param {Object} [thisObj] |
| 38 | */ |
| 39 | function some(fn, thisObj) { |
| 40 | for (const key in cache) { |
| 41 | const item = cache[key]; |
| 42 | // Might be already deleted by fn |
| 43 | if (item && fn.call(thisObj, item.value, key)) { |
| 44 | return true; |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | function pop(key, def) { |
| 49 | const value = get(key, def); |
| 50 | del(key); |
| 51 | return value; |
| 52 | } |
| 53 | function put(key, value, lifetime) { |
| 54 | reschedule(cache[key] = lifetime ? { value, lifetime } : { value }, lifetime); |
| 55 | return value; |
| 56 | } |
| 57 | function del(key) { |
| 58 | const data = cache[key]; |
| 59 | if (data) { |
| 60 | delete cache[key]; |
no outgoing calls
no test coverage detected