Activity 9: Data Structure in Typescript
Data Structures in TypeScript:
Data structures play a crucial role in programming by organizing and storing data efficiently. In TypeScript, the strong typing system enhances the use of data structures in several ways:
Type Safety: TypeScript's strong typing system ensures that data structures are used consistently with the intended types. This helps prevent runtime errors and enhances code reliability.
Code Clarity: By explicitly defining the types of elements in data structures, TypeScript code becomes more readable and self-explanatory. Developers can easily understand the structure and usage of data collections.
Intellisense Support: TypeScript's strong typing enables IDEs to provide intelligent code completion and suggestions while working with data structures. This feature improves developer productivity and reduces errors.
Enhanced Maintenance: Strong typing makes it easier to refactor code related to data structures. Since types are explicitly declared, changes can be made with confidence, knowing that the compiler will catch any type mismatches.
Performance Optimization: TypeScript's type system allows developers to optimize data structure implementations based on specific data types. This optimization can lead to better performance in terms of memory usage and execution speed.
Data Structures in TypeScript:
Arrays:
Definition: Arrays in TypeScript are used to store a collection of elements of the same type. They are accessed by index and can dynamically grow or shrink.
Key Features: Random access to elements, efficient for indexing, supports various operations like push, pop, shift, and unshift.
Use Cases: Arrays are commonly used for storing lists of items, managing ordered data, and implementing algorithms like sorting and searching.
Time Complexity:
Insert: O(n)
Delete: O(n)
Search: O(n)
Example Code:
let numbers: number[] = [1, 2, 3, 4, 5]; numbers.push(6); // Adding element numbers.pop(); // Removing element let element = numbers[2]; // Accessing element
Tuple:
Definition: Tuples are arrays with a fixed number of elements where each element may be of a different type.
Key Features: Fixed-size, type-safe, can contain elements of different types.
Use Cases: Suitable for representing multiple values of different types in a single variable.
Example Code:
let person: [string, number] = ["Alice", 30]; console.log(person[0]); // Accessing tuple element
ArrayList (Dynamic Arrays):
Definition: Dynamic arrays in TypeScript can grow or shrink in size based on the number of elements they contain.
Key Features: Automatic resizing, efficient for appending elements.
Use Cases: Used when the size of the array is not known beforehand and needs to change dynamically.
Example Code: (Dynamic resizing not explicitly handled in TypeScript)
let dynamicArray: number[] = []; dynamicArray.push(10); // Adding element
Stack:
Definition: A stack is a data structure that follows the Last In First Out (LIFO) principle.
Key Features: Supports push (add element), pop (remove element), and peek (access top element) operations.
Use Cases: Function call stack, expression evaluation, backtracking algorithms.
Example Code
let stack: number[] = []; stack.push(10); // Push let topElement = stack.pop(); // Pop
Queue:
Definition: A queue follows the First In First Out (FIFO) principle.
Key Features: Enqueue (add element at the rear), dequeue (remove element from the front) operations.
Use Cases: Task scheduling, breadth-first search, printer queues.
Example Code:
let queue: number[] = []; queue.push(10); // Enqueue let frontElement = queue.shift(); // Dequeue
LinkedList:
Definition: Linked lists consist of nodes where each node contains data and a reference to the next node.
Key Features: Dynamic size, efficient insertion and deletion.
Use Cases: Implementation of stacks, queues, adjacency lists in graphs.
Example Code: (Singly linked list example)
class Node { data: number; next: Node | null; constructor(data: number) { this.data = data; this.next = null; } }
HashMap (or Object/Map):
Definition: A key-value pair data structure where keys are unique.
Key Features: Fast lookup, key-value association.
Use Cases: Caching, indexing, implementing dictionaries.
Example Code:
let map = new Map<string, number>(); map.set("one", 1); // Insert map.delete("one"); // Delete let value = map.get("one"); // Search
Set:
Definition: A collection of unique elements with no duplicates.
Key Features: Ensures uniqueness, supports operations like add, delete, and check.
Use Cases: Finding unique elements, set operations like union, intersection.
Example Code:
let uniqueSet = new Set<number>(); uniqueSet.add(5); // Add element uniqueSet.delete(5); // Remove element let hasElement = uniqueSet.has(5); // Check element
Tree:
Definition: Trees are hierarchical data structures with a root node and child nodes.
Key Features: Binary trees have at most two children per node, BST maintains ordering.
Use Cases: Searching, sorting, hierarchical data representation.
Example Code: (Binary Search Tree example)
class TreeNode { value: number; left: TreeNode | null; right: TreeNode | null; constructor(value: number) { this.value = value; this.left = null; this.right = null; } }