CList - An Array Adapter Class which supports unique Elements
Introduction
Script
CList.js
implements a JavaScript Object CList
which is used to adapt an Array for ease of
maintaining a list of unique values with no duplicates.
- Constructor
-
- CList(Array aArray)
-
Constructs an instance of a CList object which adapts the specified Array
aArray. IfaArrayis not specified, an empty array will be used to initialize theCList.
- Properties
-
- Array mArray
-
mArrayis the array instance which will be used to contain the list of unique values.
- Methods
-
- getLength()
-
getLength()returns the length of themArrayarray. - getAt(Number aIndex)
-
getAt()returns the element at indexaIndex. - removeAll()
-
removeAll()removes all elements from theCList. - removeAt(Number aIndex)
-
removeAt()removes the element at indexaIndexfrom theCList. - insertAt(Object aObject, Number aIndex)
-
insertAt()inserts the objectaObjectinto theCListat the position specified by theaIndexindex. - findIndexOf(Object aObject)
-
findIndexOf()returns the index of the specified objectaObjectin theCListor-1if the object is not in the list. - addUnique(Object aObject)
-
addUnique()appends the specifiedaObjectto theCListif it is not already contained in the list. - removeUnique(Object aObject)
-
removeUnique()removes the specified objectaObjectfrom theCList.
Example 1
function assert(aCondition)
{
if (!aCondition)
{
alert('There was an internal error in CList');
}
}
function doExample1()
{
var list = new CList();
assert(list.getLength() == 0);
list.addUnique(1);
assert(list.getLength() == 1);
assert(list.mArray.toString() == '1');
list.addUnique(1);
assert(list.getLength() == 1);
assert(list.mArray.toString() == '1');
list.addUnique(2);
assert(list.getLength() == 2);
assert(list.mArray.toString() == '1,2');
list.addUnique(3);
assert(list.getLength() == 3);
assert(list.mArray.toString() == '1,2,3');
alert('Result after adding 1,1,2,3 = ' + list.mArray.toString());
list.removeUnique(2);
assert(list.getLength() == 2);
assert(list.mArray.toString() == '1,3');
alert('Result after removing 2 = ' + list.mArray.toString());
list.removeUnique(1);
list.removeUnique(3);
assert(list.getLength() == 0);
list = new CList( [1, 2, 3] );
var length = list.getLength();
var s = '';
for (var i = 0; i < length; ++i)
{
if (i != 0)
{
s += ',';
}
s += list.getAt(i);
}
assert(s == '1,2,3');
list.removeAll();
assert(list.getLength() == 0);
assert(list.mArray.toString() == '');
}
