UNPKG

661 BJavaScriptView Raw
1"use strict";
2
3// protect a function and cache multiple calls with same parameters
4// cache only forward the 1st parameter
5
6
7module.exports = function(fn, timeout = 3600 * 1000, gc_interval = 1) {
8 var cache = {};
9 var last_call = Date.now();
10
11
12 return function(arg) {
13
14 if(Date.now() - last_call > timeout / gc_interval) {
15 last_call = Date.now();
16 for(var k of Object.keys(cache)) {
17 if(cache[k].expires < last_call)
18 delete cache[k];
19 }
20 }
21
22 if(arg in cache)
23 return cache[arg].value;
24
25 cache[arg] = {expires : Date.now() + timeout, value : fn.apply(this, arguments)};
26
27 return cache[arg].value;
28 };
29};