जैसा कि अन्य उत्तरों का उल्लेख है, दुर्भाग्य से कमजोर मानचित्र जैसी कोई चीज़ नहीं है, जैसे जावा/सी # में है।
के चारों ओर एक काम के रूप में, मैं इस CacheMap
कि चारों ओर की वस्तुओं की अधिकतम संख्या रहता है बनाया है, और समय की एक निर्धारित अवधि में उनके उपयोग को ट्रैक करता है ताकि आप:
- हमेशा कम से कम पहुँचा वस्तु निकालने के लिए, जब आवश्यक
- मेमोरी रिसाव न बनाएं।
यहां कोड है।
"use strict";
/**
* This class keeps a maximum number of items, along with a count of items requested over the past X seconds.
*
* Unfortunately, in JavaScript, there's no way to create a weak map like in Java/C#.
* See https://stackoverflow.com/questions/25567578/garbage-collected-cache-via-javascript-weakmaps
*/
module.exports = class CacheMap {
constructor(maxItems, secondsToKeepACountFor) {
if (maxItems < 1) {
throw new Error("Max items must be a positive integer");
}
if (secondsToKeepACountFor < 1) {
throw new Error("Seconds to keep a count for must be a positive integer");
}
this.itemsToCounts = new WeakMap();
this.internalMap = new Map();
this.maxItems = maxItems;
this.secondsToKeepACountFor = secondsToKeepACountFor;
}
get(key) {
const value = this.internalMap.get(key);
if (value) {
this.itemsToCounts.get(value).push(CacheMap.getCurrentTimeInSeconds());
}
return value;
}
has(key) {
return this.internalMap.has(key);
}
static getCurrentTimeInSeconds() {
return Math.floor(Date.now()/1000);
}
set(key, value) {
if (this.internalMap.has(key)) {
this.internalMap.set(key, value);
} else {
if (this.internalMap.size === this.maxItems) {
// Figure out who to kick out.
let keys = this.internalMap.keys();
let lowestKey;
let lowestNum = null;
let currentTime = CacheMap.getCurrentTimeInSeconds();
for (let key of keys) {
const value = this.internalMap.get(key);
let totalCounts = this.itemsToCounts.get(value);
let countsSince = totalCounts.filter(count => count > (currentTime - this.secondsToKeepACountFor));
this.itemsToCounts.set(value, totalCounts);
if (lowestNum === null || countsSince.length < lowestNum) {
lowestNum = countsSince.length;
lowestKey = key;
}
}
this.internalMap.delete(lowestKey);
}
this.internalMap.set(key, value);
}
this.itemsToCounts.set(value, []);
}
size() {
return this.internalMap.size;
}
};
और आप इसे इतना पसंद किया फोन:
// Keeps at most 10 client databases in memory and keeps track of their usage over a 10 min period.
let dbCache = new CacheMap(10, 600);
स्रोत
2017-10-30 14:03:00
मुझे लगता है कि इस सवाल का विशेष रूप से जावास्क्रिप्ट, नहीं जावा या जो 'WeakReference' /' WeakHashMap' कुछ अन्य भाषा के लिए बात कर रहा है। समस्या यह है कि जावास्क्रिप्ट में केवल 'वीक हैशमैप' जैसा कुछ है, लेकिन 'वीक रेफरेंस' के बराबर नहीं है। –
@ Qantas94Heavy: वास्तव में ऐसा है। शायद मुझे यह संकेत देना चाहिए था कि जावास्क्रिप्ट केवल पहले का समर्थन करता है, दुर्भाग्य से ऐसा नहीं है कि मुझे संदेह है कि ओपी वास्तव में चाहता है। क्या आपको संपादन पसंद है? – supercat