1 | 'use strict';
|
2 |
|
3 | var Gun = require('../../gun');
|
4 |
|
5 | var cache = {};
|
6 | var timeout = null;
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | function gc () {
|
15 | var now = Date.now();
|
16 | var oldest = now;
|
17 | var maxAge = 5 * 60 * 1000;
|
18 |
|
19 | Gun.obj.map(cache, function (time, id) {
|
20 | oldest = Math.min(now, time);
|
21 |
|
22 | if ((now - time) < maxAge) {
|
23 | return;
|
24 | }
|
25 |
|
26 | delete cache[id];
|
27 | });
|
28 |
|
29 | var done = Gun.obj.empty(cache);
|
30 |
|
31 |
|
32 | if (done) {
|
33 | timeout = null;
|
34 | return;
|
35 | }
|
36 |
|
37 |
|
38 | var elapsed = now - oldest;
|
39 |
|
40 |
|
41 | var nextGC = maxAge - elapsed;
|
42 |
|
43 |
|
44 | timeout = setTimeout(gc, nextGC);
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | function duplicate (id) {
|
53 |
|
54 |
|
55 | var existing = cache.hasOwnProperty(id);
|
56 |
|
57 |
|
58 | duplicate.track(id);
|
59 |
|
60 | return existing;
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | duplicate.track = function (id) {
|
69 | cache[id] = Date.now();
|
70 |
|
71 |
|
72 | if (!timeout) {
|
73 | gc();
|
74 | }
|
75 |
|
76 | return id;
|
77 | };
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | duplicate.track.newID = function (chars) {
|
85 | var id = Gun.text.random(chars);
|
86 |
|
87 | return duplicate.track(id);
|
88 | };
|
89 |
|
90 | module.exports = duplicate;
|