I really wanted to have the ability to make collections in JavaScript:
function LinkedItem() {
this.Item = null;
this.NextItem = null;
}
function Collection() {
var _root = new LinkedItem();
var _currentItem = _root;
var _resetEnumerator = true;
var INDEX_OUT_OF_RANGE = "Index out of range.";
this.Current = function() {
return _currentItem.Item;
};
this.Add = function (item) {
if (_currentItem.Item == null)
_currentItem.Item = item;
else {
while (this.MoveNext()) {}
_currentItem.NextItem = new LinkedItem();
_currentItem = _currentItem.NextItem;
_currentItem.Item = item;
}
};
this.Remove = function (item) {
var index = this.IndexOf(item);
};
this.RemoveAt = function (index) {
if (index <>= this.Count())
throw new Error(INDEX_OUT_OF_RANGE);
var itmBefore = this.ItemAt(index-1);
var itmMiddle = _currentItem.NextItem;
var itmAfter = itmMiddle.NextItem;
itmBefore.NextItem = (itmAfter != null) ? itmAfter : null;
};
this.IndexOf = function (item) {
counter = -1;
while(this.MoveNext()) {
counter++;
if (this.Compare(item, _currentItem.Item)) {
_resetEnumerator = true;
return counter;
}
}
return -1;
};
this.Compare = function (item1, item2) {
return (item1 == item2) ? 1 : 0;
};
this.MoveNext = function()
{
if (_resetEnumerator) {
_currentItem = _root;
_resetEnumerator = false;
return true;
}
if (_currentItem.NextItem instanceof LinkedItem) {
_currentItem = _currentItem.NextItem;
return true;
} else {
_resetEnumerator = true;
return false;
}
}
this.Loop = function() {
if (_resetEnumerator) {
_currentItem = _root;
_resetEnumerator = false;
return true;
}
if (_currentItem.NextItem instanceof LinkedItem)
_currentItem = _currentItem.NextItem;
else {
_currentItem = _root;
}
return true;
};
this.ItemAt = function (index) {
if (index >= this.Count())
throw new Error(INDEX_OUT_OF_RANGE);
counter = 0;
while (this.MoveNext()) {
if (counter++ == index) {
_resetEnumerator = true;
break;
}
}
return _currentItem;
};
this.Count = function() {
counter = 0;
while (this.MoveNext()) counter++;
return counter;
};
}
Wednesday, August 17, 2005
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment