-
Notifications
You must be signed in to change notification settings - Fork 183
/
lfu-map.js
83 lines (73 loc) · 2.69 KB
/
lfu-map.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use strict";
var Shim = require("./shim");
var LfuSet = require("./lfu-set");
var GenericCollection = require("./generic-collection");
var GenericMap = require("./generic-map");
var PropertyChanges = require("./listen/property-changes");
var MapChanges = require("./listen/map-changes");
module.exports = LfuMap;
function LfuMap(values, maxLength, equals, hash, getDefault) {
if (!(this instanceof LfuMap)) {
return new LfuMap(values, maxLength, equals, hash, getDefault);
}
equals = equals || Object.equals;
hash = hash || Object.hash;
getDefault = getDefault || Function.noop;
this.contentEquals = equals;
this.contentHash = hash;
this.getDefault = getDefault;
this.store = new LfuSet(
undefined,
maxLength,
function keysEqual(a, b) {
return equals(a.key, b.key);
},
function keyHash(item) {
return hash(item.key);
}
);
this.length = 0;
this.addEach(values);
}
LfuMap.LfuMap = LfuMap; // hack so require("lfu-map").LfuMap will work in MontageJS
Object.addEach(LfuMap.prototype, GenericCollection.prototype);
Object.addEach(LfuMap.prototype, GenericMap.prototype);
Object.addEach(LfuMap.prototype, PropertyChanges.prototype);
Object.addEach(LfuMap.prototype, MapChanges.prototype);
Object.defineProperty(LfuMap.prototype,"size",GenericCollection._sizePropertyDescriptor);
LfuMap.from = GenericCollection.from;
LfuMap.prototype.constructClone = function (values) {
return new this.constructor(
values,
this.maxLength,
this.contentEquals,
this.contentHash,
this.getDefault
);
};
LfuMap.prototype.log = function (charmap, stringify) {
stringify = stringify || this.stringify;
this.store.log(charmap, stringify);
};
LfuMap.prototype.stringify = function (item, leader) {
return leader + JSON.stringify(item.key) + ": " + JSON.stringify(item.value);
};
LfuMap.prototype.addMapChangeListener = function () {
if (!this.dispatchesMapChanges) {
// Detect LFU deletions in the LfuSet and emit as MapChanges.
// Array and Heap have no store.
// Dict and FastMap define no listeners on their store.
var self = this;
this.store.addBeforeRangeChangeListener(function(plus, minus) {
if (plus.length && minus.length) { // LFU item pruned
self.dispatchBeforeMapChange(minus[0].key, undefined);
}
});
this.store.addRangeChangeListener(function(plus, minus) {
if (plus.length && minus.length) {
self.dispatchMapChange(minus[0].key, undefined);
}
});
}
MapChanges.prototype.addMapChangeListener.apply(this, arguments);
};