forked from Yomguithereal/mnemonist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparse-multi-array.js
118 lines (92 loc) · 2.23 KB
/
sparse-multi-array.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* Mnemonist SparseMultiArray
* ===========================
*
* Memory-efficient representation of an array of arrays whose indices are
* not densely populated. It has a read/write overhead but is very lean in
* memory because it does not need to create subarrays. This structure is
* particularly suited to indices that will need to merge arrays anyway
* when queried and that are quite heavy and often hit such as a QuadTree.
*/
var Iterator = require('obliterator/iterator');
/**
* SparseMultiArray.
*
* @constructor
*/
function SparseMultiArray() {
this.clear();
}
/**
* Method used to clear the structure.
*
* @return {undefined}
*/
SparseMultiArray.prototype.clear = function() {
// Properties
this.size = 0;
this.dimension = 0;
this.tails = {};
this.lengths = {};
this.pointers = [0];
this.items = [];
};
SparseMultiArray.prototype.set = function(index, item) {
var tail = this.tails[index],
pointer;
pointer = this.pointers.length;
// This linked list does not exist yet. Let's create it
if (typeof tail !== 'number') {
this.dimension++;
this.pointers.push(0);
this.lengths[index] = 1;
}
// Appending to the list
else {
this.pointers.push(tail);
this.lengths[index]++;
}
this.tails[index] = pointer;
this.items.push(item);
this.size++;
return this;
};
SparseMultiArray.prototype.get = function(index) {
var pointer = this.tails[index];
if (typeof pointer !== 'number')
return;
var length = this.lengths[index],
i = length;
var array = new Array(length);
while (pointer !== 0) {
array[--i] = this.items[~-pointer];
pointer = this.pointers[pointer];
}
return array;
};
SparseMultiArray.prototype.has = function(index) {
var tail = this.tails[index];
return typeof tail === 'number';
};
SparseMultiArray.prototype.containers = function() {
return new Iterator(function() {
});
};
// TODO: version static cells + nb of objects low level taking a array constructor
// online creation
// #.count
// #.entries
// #.containers
// #.associations
// #.values
// #.keys
/**
* Convenience known methods.
*/
SparseMultiArray.prototype.inspect = function() {
return this;
};
/**
* Exporting.
*/
module.exports = SparseMultiArray;