morganrallen / histarray

Versioning array in Javascript

morganrallen (author)
Fri Sep 19 10:59:24 -0700 2008
commit  4bff570650eacdfdca19be5f7f05055c71d5729b
tree    6b6f4b6c0bd6503e3f78e503685e18e03b8afb13
parent  81bac5a8f7a7a9e0a2a4db2dfc7cdb3a94ee539f
histarray / histarray.js
100644 130 lines (122 sloc) 2.464 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
function histarray()
{
for(var i = 0; i < arguments.length; i++)
this._add(arguments[i], i);
 
this.__defineSetter__('revision', function(v)
{
return (v > this.length) ?
this.revision :
this._revision = v;
});
this.__defineGetter__('revision', function()
{
return this._revision;
});
this.__defineGetter__('prev', function()
{
return (this.revision != 0) ?
(function(self)
{
var a = Array();
for(var i in self._elements)
a.push(self._elements[i][self.revision - 1]);
return a;
})(this) :
null;
});
this.__defineGetter__('nxt', function()
{
return (this.revision < this.revisions) ?
(function(self)
{
var a = Array();
for(var i in self._elements)
a.push(self._elements[i][self.revision + 1]);
return a;
})(this) :
null;
});
};
 
histarray.prototype =
{
length: 0,
revisions: 0,
_elements: Array(),
_revision: 0,
_add: function(e, i)
{
this._elements[i] = (function(e,self)
{
var a = Array();
for(var i = 0; i < self.revisions; i++)
a.push(null);
a.push(e);
return a;
})(e,this);
this.__defineGetter__(i, function()
{
return this._elements[i][this.revision];
});
 
this.__defineSetter__(i, function(v)
{
return this._elements[i][this.revision] = v;
});
this.length = i + 1;
},
_remove: function(i)
{
if(i < this.length)
{
var a = this._elements[i];
for(var j = i; j++ < this.length;)
this[i] = (this[i + 1]) ? this[i + 1] : null;
 
this._elements.splice(i,1);
delete this[--this.length];
return a;
}
else
{
var a = this._elements.pop();
delete this[--this.length];
return a;
}
},
// push csv or a single array
push: function()
{
if(typeof arguments[0] == 'object')
this.push.apply(this, arguments[0]);
else
{
// at the end of the timeline, so push a new revision
if(this.revision == this.revisions)
{
this.revisions++;
this._revision++;
}
// otherwise just over write the current
 
for(var i = 0; i < arguments.length; i++)
{
if(arguments[i] == null) continue;
 
if(this._elements[i])
this._elements[i][this.revision] = arguments[i];
else
this._add(arguments[i], i);
}
}
return this.length;
},
pop: function()
{
var a = this._elements.pop();
delete this[--this.length];
return a;
},
splice: function(f,t)
{
var a = Array();
for(var i = f; i < (f + t); i++)
a.push(this._remove(f));
 
return a;
}
};