UNPKG

1.7 kBJavaScriptView Raw
1'use strict';
2
3var Gun = require('../../gun');
4
5var cache = {};
6var timeout = null;
7
8/**
9 * Remove all entries in the cache older than 5 minutes.
10 * Reschedules itself to run again when the oldest item
11 * might be too old.
12 * @return {undefined}
13 */
14function 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 // Disengage GC.
32 if (done) {
33 timeout = null;
34 return;
35 }
36
37 // Just how old?
38 var elapsed = now - oldest;
39
40 // How long before it's too old?
41 var nextGC = maxAge - elapsed;
42
43 // Schedule the next GC event.
44 timeout = setTimeout(gc, nextGC);
45}
46
47/**
48 * Checks a memory-efficient cache to see if a string has been seen before.
49 * @param {String} id - A string to keep track of.
50 * @return {Boolean} - Whether it's been seen recently.
51 */
52function duplicate (id) {
53
54 // Have we seen this ID recently?
55 var existing = cache.hasOwnProperty(id);
56
57 // Add it to the cache.
58 duplicate.track(id);
59
60 return existing;
61}
62
63/**
64 * Starts tracking an ID as a possible future duplicate.
65 * @param {String} id - The ID to track.
66 * @return {String} - The same ID.
67 */
68duplicate.track = function (id) {
69 cache[id] = Date.now();
70
71 // Engage GC.
72 if (!timeout) {
73 gc();
74 }
75
76 return id;
77};
78
79/**
80 * Generate a new ID and start tracking it.
81 * @param {Number} [chars] - The number of characters to use.
82 * @return {String} - The newly created ID.
83 */
84duplicate.track.newID = function (chars) {
85 var id = Gun.text.random(chars);
86
87 return duplicate.track(id);
88};
89
90module.exports = duplicate;