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.
Veja também: JavaScript forEach()
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];
}
}
//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";
}
}
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";
}
}
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;
}
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);
}
}
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";
}
}
Semelhante ao SetItem, insere um elemento na lista no índice especificado (Listagem 6).
///Removes all elements from the Collections.
this.Clear = function () {
collection = [];
}
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;
}
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);
}
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;
}
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;
}
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);
}
}
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);
}
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);
}
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;
}
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>
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.