UNPKG

weak-dictionary

Version:
66 lines (55 loc) 1.39 kB
var WeakDictionary = function() { this._weakMap = new WeakMap(); this._keys = []; }; WeakDictionary.prototype.set = function(key, value) { this._keys.push(key); return this._weakMap.set(key, value); }; WeakDictionary.prototype.has = function(key) { return this._weakMap.has(key); }; WeakDictionary.prototype.get = function(key) { return this._weakMap.get(key); }; WeakDictionary.prototype.delete = function(key) { var result = this._weakMap.delete(key); this._keys.splice(this._keys.indexOf(key), 1); return result; }; WeakDictionary.prototype.forEach = function(cb) { var that = this; this._keys.forEach(function(key) { if (that.has(key)) cb(key, that.get(key)); }); }; WeakDictionary.prototype.clear = function() { var that = this; this._keys.forEach(function(key) { if (that.has(key)) { var value = that.get(key); if (value) that.delete(key); } }); this._weakMap = new WeakMap(); this._keys = []; }; WeakDictionary.prototype.getKeys = function() { return this._keys; }; WeakDictionary.prototype.getSize = function() { this.refresh(); return this._keys.length; }; WeakDictionary.prototype.refresh = function() { var that = this; var keysToRemove = []; this._keys.forEach(function(key) { if (!that.has(key)) { keysToRemove.push(key); } }); }; module.exports = WeakDictionary;