-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (75 loc) · 2.13 KB
/
index.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
module.exports = function createStash(){
return new Stash();
}
module.exports.Stash = Stash;
function Stash(){
this.values = [];
this.lookup = {}; // [key] = index
this.reverse = {}; // [index] = key
this.length = 0;
}
Stash.prototype = {
set: function(key,val){
key = ''+key
if( key in this.lookup ){
console.warn('key "%s" already exists in stash. deleting it first.',key)
this.del(key);
}
var index = this.values.length;
this.lookup[key] = index;
this.reverse[index] = key;
this.values.push(val)
this.length++;
return this
},
has: function(key){
return (''+key) in this.lookup;
},
get: function(key){
key = ''+key
if( key in this.lookup ){
var index = this.lookup[key];
return this.values[index];
} else console.error('tried to get "%s" that didn\'t exist',key)
return undefined;
},
del: function(key){
key = ''+key
if( key in this.lookup ){
// move the last values into the
// position of the deleted value
// to keep the array dense (and
// avoid unnecessary allocation)
var index = this.lookup[key]
, end = this.length-1;
// special case if the deleted key is last value (no need to reorder stuff)
if( index == end ){
this.values.pop();
delete this.reverse[index];
delete this.lookup[key];
this.length--;
} else if( index >= 0 && index < end ){
this.values[index] = this.values.pop();
// update the lookups
var rindex = this.values.length;
var rkey = this.reverse[rindex];
this.lookup[rkey] = index;
this.reverse[index] = rkey;
delete this.reverse[rindex];
delete this.lookup[key];
this.length--;
} else console.warn('tried to delete "%s" with an invalid index %s',key,index)
} else console.warn('tried to delete "%s" that didn\'t exist',key)
return this;
},
empty: function(){
this.values.length = 0
this.length = 0
for(var i in this.reverse){
var k = this.reverse[i]
delete this.lookup[k]
delete this.reverse[i]
}
return this;
}
}