forked from eoinsha/tick-map
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtick-map.js
More file actions
104 lines (87 loc) · 2.27 KB
/
tick-map.js
File metadata and controls
104 lines (87 loc) · 2.27 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
module.exports = TickMap;
var Map = require('pseudomap');
var Find = require('lodash.find');
var SortedIndexBy = require('lodash.sortedindexby');
function TickMap() {
if (!(this instanceof TickMap)) {
return new TickMap();
}
this.internals = {
tickSeq: [], // Ordered array of populated ticks in the map. Duplicates are allowed
bucketMap: new Map()
};
}
Object.defineProperties(TickMap.prototype, {
length: { enumerable: true, get: function() {
return this.internals.tickSeq.length;
}},
_getBucket: { enumerable: false, get: function() {
return getBucket;
}}
});
TickMap.prototype.add = function(tick, value) {
var targetIndex = SortedIndexBy(this.internals.tickSeq, tick);
this.internals.tickSeq.splice(targetIndex, 0, tick);
var bucketKey = makeBucketKey(tick);
var entry = new Entry(tick, value);
var bucket = this.internals.bucketMap.get(bucketKey);
if (!bucket) {
bucket = [ entry ];
this.internals.bucketMap.set(bucketKey, bucket);
return;
}
var bucketIndex = SortedIndexBy(bucket, entry, entryTickMap);
bucket.splice(bucketIndex, 0, entry);
}
/**
* Retrieve an item by zero-based index
*/
TickMap.prototype.item = function(index) {
var tick = this.internals.tickSeq[index];
return this.get(tick);
}
/**
* Retrieve an item by exact tick.
*
* @return The item or `undefined`
*/
TickMap.prototype.get = function(tick) {
var bucket = this._getBucket(tick);
if (bucket) {
var entry = getInBucket(bucket, tick);
if (entry) {
return entry.value;
}
}
}
/**
* Retrieves all items in the same bucket as the specified tick
*
* @return An array of items. If no items exist or no bucket exists, an empty array is returned.
*/
TickMap.prototype.getBucketItems = function(tick) {
var entries = this._getBucket(tick);
if (entries) {
return entries.map(function(entry) {
return entry.value;
});
}
return [];
}
function getBucket(tick) {
var bucketKey = makeBucketKey(tick);
return this.internals.bucketMap.get(bucketKey);
}
function getInBucket(bucket, tick) {
return Find(bucket, {tick: tick});
}
function entryTickMap(entry) {
return entry.tick;
}
function makeBucketKey(tick) {
return Math.floor(tick);
}
function Entry(tick, value) {
this.tick = tick;
this.value = value;
}