DEV Community

William Koller
William Koller

Posted on

1

O que é um ArrayList?

O ArrayList é uma estrutura de dados baseada em arrays que permite adicionar, remover e acessar elementos de forma eficiente. Diferente dos arrays tradicionais, o ArrayList cresce dinamicamente conforme novos elementos são adicionados.

Implementação do ArrayList em TypeScript

Abaixo está a implementação completa de um ArrayList genérico em TypeScript:

export class ArrayList<T> {
  private items: T[];
  private map: Map<string, T>;

  constructor(initialCapacity: number = 0) {
    this.items = new Array<T>(initialCapacity);
    this.map = new Map<string, T>();
  }

  add(element: T): void {
    this.items.push(element);
  }

  addAll(elements: T[]): void {
    this.items.push(...elements);
  }

  get(index: number): T | undefined {
    if (index < 0 || index >= this.items.length) {
      throw new Error('Index out of bounds');
    }
    return this.items[index];
  }

  set(index: number, element: T): void {
    if (index < 0 || index >= this.items.length) {
      throw new Error('Index out of bounds');
    }
    this.items[index] = element;
  }

  remove(index: number): T | undefined {
    if (index < 0 || index >= this.items.length) {
      throw new Error('Index out of bounds');
    }
    return this.items.splice(index, 1)[0];
  }

  removeElement(element: T): boolean {
    const index = this.items.indexOf(element);
    if (index !== -1) {
      this.items.splice(index, 1);
      return true;
    }
    return false;
  }

  size(): number {
    return this.items.length;
  }

  isEmpty(): boolean {
    return this.items.length === 0;
  }

  contains(element: T): boolean {
    return this.items.includes(element);
  }

  clear(): void {
    this.items = [];
  }

  toArray(): T[] {
    return [...this.items];
  }

  indexOf(element: T): number {
    return this.items.indexOf(element);
  }

  lastIndexOf(element: T): number {
    return this.items.lastIndexOf(element);
  }

  subList(fromIndex: number, toIndex: number): T[] {
    if (fromIndex < 0 || toIndex > this.items.length || fromIndex > toIndex) {
      throw new Error('Index out of bounds');
    }
    return this.items.slice(fromIndex, toIndex);
  }

  forEach(callback: (element: T, index: number) => void): void {
    this.items.forEach(callback);
  }

  sort(compareFn?: (a: T, b: T) => number): void {
    this.items.sort(compareFn);
  }

  setKeyValue(key: string, value: T): void {
    this.map.set(key, value);
  }

  getValue(key: string): T | undefined {
    return this.map.get(key);
  }

  removeKey(key: string): boolean {
    return this.map.delete(key);
  }

  hasKey(key: string): boolean {
    return this.map.has(key);
  }

  clearMap(): void {
    this.map.clear();
  }

  mapSize(): number {
    return this.map.size;
  }
}

Enter fullscreen mode Exit fullscreen mode

Explicação dos Métodos:

  • add(element: T): Adiciona um elemento à lista.

  • addAll(elements: T[]): Adiciona múltiplos elementos de uma vez.

  • get(index: number): Retorna o elemento em um índice específico.

  • set(index: number, element: T): Atualiza o elemento em um índice.

  • remove(index: number): Remove um elemento pelo índice.

  • removeElement(element: T): Remove um elemento específico.

  • size(): Retorna o tamanho atual da lista.

  • isEmpty(): Verifica se a lista está vazia.

  • contains(element: T): Verifica se um elemento está presente na lista.

  • clear(): Remove todos os elementos da lista.

  • toArray(): Retorna a lista como um array.

  • indexOf(element: T): Retorna o índice da primeira ocorrência do elemento.

  • lastIndexOf(element: T): Retorna o índice da última ocorrência do elemento.

  • subList(fromIndex: number, toIndex: number): Retorna uma sublista entre os índices fornecidos.

  • forEach(callback): Itera sobre os elementos da lista.

  • sort(compareFn): Ordena os elementos com base em uma função opcional de comparação.

Exemplo de Uso:

const list = new ArrayList<number>();
list.add(10);
list.add(20);
list.add(30);
console.log(list.get(1)); // Saída: 20
list.remove(1);
console.log(list.toArray()); // Saída: [10, 30]

Enter fullscreen mode Exit fullscreen mode

Repo no Github: https://github.com/williamkoller/array-list

Conclusão

Essa implementação do ArrayList em TypeScript oferece uma alternativa flexível para manipular listas dinâmicas de maneira eficiente. O uso de tipagem genérica permite que a lista funcione com qualquer tipo de dado, tornando-a extremamente versátil.

Se gostou do artigo, compartilhe com outros desenvolvedores! 🚀

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay