1. Welcome and Icebreaker:
- If you could invent a new data structure, what would it do?
2. Outline the Session:
- We’ll practice building a generic data structure in TypeScript (e.g., a stack or queue).
- Learning Outcomes: Apply generics to create reusable and type-safe data structures.
- Let’s get practical!
3. Concept Explanation:
- Building your own data structures helps you understand how generics work in real-world scenarios.
- We’ll use a stack (LIFO) as an example, but you can try a queue (FIFO) or another structure.
- The key is to use generics so your structure works with any type.
4. Live Coding Demonstration:
class Stack<T> {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
size(): number {
return this.items.length;
}
}
const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop()); // 2
console.log(numberStack.peek()); // 1
console.log(numberStack.size()); // 1
const stringStack = new Stack<string>();
stringStack.push("a");
stringStack.push("b");
console.log(stringStack.pop()); // "b"
5. Tasks:
- Short Exercise:
- Implement a generic
Queue<T> class with enqueue, dequeue, and size methods.
- Test your queue with both numbers and strings.
- Try building another generic data structure of your choice (e.g., a linked list or set).