Netscape DevEdge

Skip to: [content] [navigation]

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. If aArray is not specified, an empty array will be used to initialize the CList.

Properties
Array mArray

mArray is the array instance which will be used to contain the list of unique values.

Methods
getLength()

getLength() returns the length of the mArray array.

getAt(Number aIndex)

getAt() returns the element at index aIndex.

removeAll()

removeAll() removes all elements from the CList.

removeAt(Number aIndex)

removeAt() removes the element at index aIndex from the CList.

insertAt(Object aObject, Number aIndex)

insertAt() inserts the object aObject into the CList at the position specified by the aIndex index.

findIndexOf(Object aObject)

findIndexOf() returns the index of the specified object aObject in the CList or -1 if the object is not in the list.

addUnique(Object aObject)

addUnique() appends the specified aObject to the CList if it is not already contained in the list.

removeUnique(Object aObject)

removeUnique() removes the specified object aObject from the CList.

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() == '');
}
A+R