Nesse artigo vou mostrar como criar e utilizar uma lista genérica, com isso facilitando a utilização de vetores no JavaScript. Para criar a lista utilizaremos as classes no JavaScript. Consulte meu artigo que fala sobre como utilizar classes no JavaScript.

A classe List representa uma lista de objetos que podem ser acessados pelo índice, fornece métodos para pesquisar e manipular listas. Pode ser inicializada uma nova instância da classe vazia ou uma capacidade inicial especificada. Nas Listagens 1 e 2 os métodos que serão criados.

  • GetItem(index) ;
  • SetItem(index, item) ;
  • Add(item);
  • AddRange(items);
  • Insert(pos, item);
  • Clear();
  • Count();
  • Equal(x, y);
  • Find(obj);
  • Exists(obj);
  • ForEach(action);
  • RemoveAt(índex);
  • RemoveRange(índex, count);
  • GetRange(índex, count).

  function List(capacity) {
    var collection = [];
 
    if (capacity != null) {
        collection[capacity];
    }
}
Listagem 1. Criando o construtor da classe


//Get the element at the specified index
this.GetItem = function (index) {
    if (index <= collection.length - 1) {
        return collection[index];
    }
    else {
        throw "Index was out of range. Must be non-negative and less than
        the size of the collection";
    }
}
Listagem 2. Criando o método GetItem

Este método obtém o elemento no índice especifico.


///Set the element at the specified index
this.SetItem = function (index, item) {
      if (index <= collection.length - 1) {
          collection[index] = item;
      }
      else {
          throw "Index was out of range. Must be non-negative and 
          less than the size of the collection";
      }
  }
Listagem 3. Criando o método SetItem

O método SetItem coloca o elemento no índice especificado, como na Listagem 3.


///Adds an object to the end of the Collections.
this.Add = function (item) {
 collection[collection.length] = item;
}
Listagem 4. Criando o método Add

Este método adiciona um objeto no fim da lista, como mostra a Listagem 4.


///Adds the elements of the specified collection to the end of the Collections.
this.AddRange = function (items) {
  for (var i = 0; i < items.Count(); i++) {
    collection[collection.length] = items.GetItem(i);
    }
}
Listagem 5. Criando o método AddRange

O AddRange, por sua vez, adiciona elementos de uma especifica lista no fim da lista, conforme Listagem 5.


///Inserts an element into the System.Collections.Generic.List<T> at the specified index.
this.Insert = function (pos, item) {
    if (pos <= collection.length - 1) {
        collection.splice(pos, 0, item);
    }
    else {
        throw "Index must be within the bounds of the List";
    }
}
Listagem 6. Criando o método Insert

Semelhante ao SetItem, insere um elemento na lista no índice especificado (Listagem 6).


///Removes all elements from the Collections.
this.Clear = function () {
    collection = [];
}
Listagem 7. Criando o método Clear

Remova todos os elementos da lista, conforme a Listagem 7.


///Gets the number of elements actually contained in the Collections.
this.Count = function () {
 return collection.length;
}
Listagem 8. Criando o método Count

Na Listagem 8 o Count obtém o número de elementos atual contidos na lista.


///Determines whether the specified object instances are considered equal.
this.Equal = function (x, y) {
 return (x === y);
}
Listagem 9. Criando o método Equal

Comum em várias linguagens, esse método da Listagem 9 compara dois objetos.


///Searchs the element in collection.
this.Find = function (obj) {
  var index = -1;
    for (var i = 0; i < collection.length; i++) {
        var item = collection[i];
     
        if (this.Equal(item, obj)) {
             index = i;
             reak;
        }
    }
     
  return index;
}
Listagem 10. Criando o método Find

Como o nome sugere, o Find é utilizado para procurar um elemento na lista (Listagem 10).


///Checks whether the element exists in the collection
this.Exists = function (obj) {
  var isFind = false; 
  if (this.Find(obj) > -1) {
    isFind = true;
  }
     
  return isFind;
}
Listagem 11. Criando o método Exists

Na Listagem 11, se o elemento procurado existir na lista, este método retorna true, caso contrário, retorna false.


///Performs the specified action on each element of the Collections.
this.ForEach = function (action) {
  for (var i = 0; i < collection.length; i++) {
    var item = collection[i];
     
    action(item);
  }
}
Listagem 12. Criando o método ForEach

A Listagem 12 percorre os elementos da lista executando uma ação com cada um.


///Removes the element at the specified index of the collection
this.RemoveAt = function (index) {
  collection.splice(index, 1);
}
Listagem 13. Criando o método RemoveAt

Remove o elemento no índice especificado da lista (Listagem 13).


///Removes a range of elements from the collection
this.RemoveRange = function (index, count) {
  collection.splice(index, count);
}
Listagem 14. Criando o método RemoveRange

A Listagem 14 remove um intervalo de elementos da lista.


///Creates a shallow copy of a range of elements in the source collection
this.GetRange = function (index, count) {
  newList = new List();
     
  var indexCount = 0;
     
    for (var i = index; i < collection.length; i++) {
        var item = collection[i];
     
        if (indexCount < count) {
            newList.Add(item);
        }
        else {
            break;
        }
     
        indexCount++;
    }
     
    return newList;
}
Listagem 15. Criando o método GetRange

Na Listagem 15 criamos uma cópia superficial de uma série de elementos da lista de origem.

Já na Listagem 16 temos um exemplo de como usar a lista genérica.

<html>
<head>
<title>List</title>
         
<script language="javascript" type="text/javascript" src="List.js"></script>
<script language="javascript" type="text/javascript">
  function onLoad() {
  var oList = new List();
  var oList2 = new List();
                 
    oList.Add('Item 1');
     
    oList2.Add('Item Sub 1');
    oList2.Add('Item Sub 3');
     
  var itemSub2 = 'Item Sub 2';
     
    oList2.Insert(1, itemSub2);
     
    oList.AddRange(oList2);
     
  for (var i = 0; i < oList.Count(); i++) {
    document.writeln(oList.GetItem(i) + "<br>");
  }
     
  document.writeln('oList2 - Exists<br>');
     
    if (oList2.Exists(itemSub2)) {
        document.writeln('Yes<br>');
    }
    else {
        document.writeln('No<br>');
    }
     
    document.writeln('oList - Exists<br>');
     
    var item2 = 'Item 2';
     
    if (oList.Exists(item2)) {
        document.writeln('Yes<br>');
    }
    else {
        document.writeln('No<br>');
    }
     
    oList.Add(item2);
     
    document.writeln('oList Index = ' + oList.Find(item2) + "<br>");
     
        var copyList = oList;
     
        document.writeln('Equal = ' + oList.Equal(oList, copyList) + "<br>");
     
        copyList.ForEach(function (obj) {
            document.writeln(obj + "<br>");
        }
     
            document.writeln("<br>GetRange()<br>");
     
            var rangeList = copyList.GetRange(2, 2);
     
            rangeList.ForEach(function (obj) {
            document.writeln(obj + "<br>");
            }
        );
  }
</script>
</head>
<body onload="onLoad();">
     
</body>
</html>
Listagem 16. Exemplo de utilização da lista genérica
Resultado da utilização da lista
Figura 1. Resultado da utilização da lista

Com isso, finalizamos este artigo no qual foi apresentada uma solução simples e eficiente para o desenvolvimento de uma classe para manipulação de uma lista genérica de objetos na linguagem JavaScript.