Implementing a Custom Array Data Structure in TypeScript
Are you looking to deepen your understanding of data structures in TypeScript? Let's dive into creating a custom array implementation that goes beyond the built-in array type. This article will guide you through building an ArrayList
class that mimics some of the functionality of JavaScript's native arrays.
The ArrayList Class
We'll start by defining our ArrayList
class:
class ArrayList<T> {
private items: T[];
private size: number;
constructor() {
this.items = [];
this.size = 0;
}
// Methods will be implemented here
}
Our ArrayList
is generic, allowing it to hold any type T
. We use a private array items
to store elements and keep track of the size
.
Basic Operations
Let's implement some fundamental array operations:
1. Adding Elements
public add(element: T): void {
this.items[this.size] = element;
this.size++;
}
2. Getting Elements
public get(index: number): T {
if (index < 0 || index >= this.size) {
throw new Error("Index out of bounds");
}
return this.items[index];
}
3. Removing Elements
public remove(index: number): T {
if (index < 0 || index >= this.size) {
throw new Error("Index out of bounds");
}
const removedItem = this.items[index];
for (let i = index; i < this.size - 1; i++) {
this.items[i] = this.items[i + 1];
}
this.size--;
return removedItem;
}
Additional Functionality
Let's add some more methods to enhance our ArrayList
:
4. Getting the Size
public getSize(): number {
return this.size;
}
5. Checking if Empty
public isEmpty(): boolean {
return this.size === 0;
}
6. Clearing the ArrayList
public clear(): void {
this.items = [];
this.size = 0;
}
Using Our ArrayList
Here's how we can use our custom ArrayList
:
const list = new ArrayList<number>();
list.add(1);
list.add(2);
list.add(3);
console.log(list.get(1)); // Output: 2
console.log(list.getSize()); // Output: 3
list.remove(1);
console.log(list.getSize()); // Output: 2
console.log(list.get(1)); // Output: 3
list.clear();
console.log(list.isEmpty()); // Output: true
Conclusion
By implementing this custom ArrayList
, we've gained insight into how arrays work under the hood. This knowledge can be invaluable when optimizing code or working with more complex data structures.
Remember, while this implementation is educational, TypeScript's built-in arrays are highly optimized and should be preferred for most use cases. However, understanding these concepts will make you a more proficient TypeScript developer.
Happy coding!
Top comments (0)