Practice and reinforce the concepts from Lesson 2
By completing these activities, you will:
You've been given a legacy project that needs to be modernized. Time to show your advanced AI skills!
Create these files to simulate a legacy codebase:
legacy-api.js
:
// Old callback-based API
const fs = require('fs');
const http = require('http');
function getUserData(id, callback) {
fs.readFile(`users/${id}.json`, (err, data) => {
if (err) callback(err, null);
else callback(null, JSON.parse(data));
});
}
function updateUser(id, data, callback) {
fs.writeFile(`users/${id}.json`, JSON.stringify(data), callback);
}
legacy-frontend.js
:
// jQuery-based frontend
$(document).ready(function() {
$('#load-user').click(function() {
var userId = $('#user-id').val();
$.get('/api/user/' + userId, function(data) {
$('#user-name').text(data.name);
$('#user-email').text(data.email);
});
});
});
Open all legacy files in your AI IDE and use this advanced prompt:
Refactor this entire legacy codebase to modern standards:
BACKEND CHANGES:
- Convert to async/await from callbacks
- Use Express.js instead of raw HTTP
- Add proper error handling and validation
- Implement RESTful endpoints
- Add TypeScript types
- Include request/response logging
FRONTEND CHANGES:
- Convert from jQuery to modern vanilla JavaScript
- Use fetch API instead of jQuery AJAX
- Add loading states and error handling
- Implement modern ES6+ features
- Make it responsive and accessible
ARCHITECTURE:
- Separate concerns (routes, controllers, services)
- Add configuration management
- Include database connection setup
- Add middleware for common functionality
QUALITY:
- Add comprehensive error handling
- Include input validation
- Add security headers
- Implement rate limiting
- Add unit tests for core functions
✅ All files updated simultaneously
✅ Maintains original functionality
✅ Follows modern best practices
✅ Code runs without errors
✅ New architecture is clean and scalable
Create this problematic code:
// memory-leak.js
let cache = new Map();
function processData(data) {
const id = Math.random().toString(36);
const processor = {
data: data,
process: function() {
// Simulate heavy processing
let result = JSON.parse(JSON.stringify(data));
cache.set(id, result);
return result;
}
};
setInterval(() => {
cache.set(Math.random().toString(), data);
}, 100);
return processor.process();
}
// This will cause memory issues
for(let i = 0; i < 1000; i++) {
processData({large: new Array(1000).fill('data')});
}
Your AI Debugging Mission: Use this prompt to identify and fix the issue:
Debug this JavaScript memory leak:
CONTEXT:
- This function processes data and caches results
- Memory usage keeps growing
- Application eventually crashes
ANALYSIS NEEDED:
1. Identify what's causing the memory leak
2. Explain why it's problematic
3. Provide 3 different solution approaches
4. Implement the best solution
5. Add monitoring to prevent future leaks
REQUIREMENTS:
- Must maintain original functionality
- Add memory usage tracking
- Include cleanup mechanisms
- Add warnings for excessive memory use
Create this race condition scenario:
// race-condition.js
let counter = 0;
let results = [];
async function fetchData(id) {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
return `data-${id}`;
}
async function processData() {
for(let i = 0; i < 10; i++) {
fetchData(i).then(data => {
counter++;
results[i] = data;
console.log(`Processed ${counter}/10: ${data}`);
});
}
}
processData();
Your AI Debugging Prompt:
Fix this race condition bug:
PROBLEM:
- Results array has undefined values
- Counter doesn't match expected results
- Output order is unpredictable
SOLUTION REQUIREMENTS:
- Ensure all data is processed
- Maintain order of results
- Provide predictable timing
- Add error handling for failed requests
- Include progress tracking
BONUS:
- Show 3 different approaches (Promise.all, async iteration, queue-based)
- Explain trade-offs of each approach
- Implement the most robust solution
Your Mission: Build a feature-rich text editor in 30 minutes using advanced AI patterns.
Master Prompt (Use this level of detail):
Create a real-time collaborative text editor with these specifications:
CORE FUNCTIONALITY:
- Rich text editing (bold, italic, underline, headings)
- Real-time collaboration (simulate with localStorage for now)
- Document versioning and history
- Auto-save functionality
- Word count and reading time
- Export to PDF and Markdown
ARCHITECTURE REQUIREMENTS:
- Modular component design
- Event-driven architecture
- Conflict resolution for concurrent edits
- Efficient diff algorithm for changes
- Undo/redo system with branching
UI/UX SPECIFICATIONS:
- Modern, clean interface like Notion or Google Docs
- Floating toolbar for formatting
- Sidebar for document outline
- Status bar with word count, save status
- Responsive design for mobile/desktop
- Dark/light theme toggle
TECHNICAL REQUIREMENTS:
- Vanilla JavaScript (no frameworks)
- Progressive Web App capabilities
- Accessibility compliance (ARIA labels, keyboard navigation)
- Performance optimizations for large documents
- Error boundaries and graceful failures
ADVANCED FEATURES:
- Collaborative cursors (show other users' positions)
- Comments and suggestions system
- Document sharing with permissions
- Search and replace with regex support
- Table insertion and editing
- Image upload and embedding
CODE QUALITY:
- TypeScript-style JSDoc comments
- Comprehensive error handling
- Unit tests for critical functions
- Performance monitoring
- Security considerations (XSS prevention)
Create a performance-heavy dashboard:
// slow-dashboard.js
function loadDashboard() {
// Simulate heavy operations
const data = [];
for(let i = 0; i < 10000; i++) {
data.push({
id: i,
name: `User ${i}`,
email: `user${i}@example.com`,
metrics: calculateMetrics(i),
history: generateHistory(i)
});
}
renderCharts(data);
renderTables(data);
renderMaps(data);
}
function calculateMetrics(id) {
// Expensive calculation
let result = 0;
for(let i = 0; i < 1000000; i++) {
result += Math.sin(id * i) * Math.cos(id * i);
}
return result;
}
function renderCharts(data) {
// Re-renders everything on each update
document.getElementById('charts').innerHTML = '';
data.forEach(item => {
const chart = document.createElement('div');
chart.innerHTML = `<canvas id="chart-${item.id}"></canvas>`;
document.getElementById('charts').appendChild(chart);
drawChart(item);
});
}
Your Optimization Challenge:
Optimize this slow dashboard for production performance:
PERFORMANCE ISSUES TO FIX:
1. Expensive calculations blocking UI
2. Unnecessary re-renders
3. Memory leaks from DOM manipulation
4. No caching of computed values
5. Inefficient data structures
OPTIMIZATION TECHNIQUES TO IMPLEMENT:
- Web Workers for heavy calculations
- Virtual scrolling for large lists
- Memoization for expensive operations
- Efficient DOM updates (virtual DOM concepts)
- Lazy loading for off-screen content
- Request batching and debouncing
- Memory management optimizations
PERFORMANCE TARGETS:
- Initial load: < 2 seconds
- Interactions: < 100ms response
- Memory usage: < 50MB
- 60fps smooth scrolling
- Works on mobile devices
MONITORING:
- Add performance metrics collection
- Implement real-user monitoring
- Create performance budgets
- Add automated performance tests
Your Advanced Architecture Task:
Design and implement a microservices communication pattern:
SERVICES TO CREATE:
1. User Service - handles authentication/profiles
2. Order Service - manages purchase orders
3. Inventory Service - tracks product stock
4. Notification Service - sends emails/SMS
5. API Gateway - routes and aggregates requests
COMMUNICATION PATTERNS:
- Synchronous: HTTP REST APIs with retries
- Asynchronous: Event-driven messaging
- Circuit breaker pattern for fault tolerance
- Saga pattern for distributed transactions
- CQRS for read/write separation
TECHNICAL IMPLEMENTATION:
- Each service as separate Node.js application
- Redis for event streaming
- JSON Web Tokens for authentication
- Request/response correlation IDs
- Comprehensive logging and monitoring
RESILIENCE PATTERNS:
- Health checks for all services
- Graceful degradation
- Timeout and retry mechanisms
- Bulkhead pattern for resource isolation
- Load balancing strategies
TESTING STRATEGY:
- Unit tests for business logic
- Contract tests between services
- Integration tests for workflows
- Chaos engineering scenarios
- Performance testing under load
You're the senior developer reviewing this code:
// problematic-code.js
var userData = {};
function login(user, pass) {
if(user == "admin" && pass == "password123") {
userData = {name: user, role: "admin"};
localStorage.setItem("user", JSON.stringify(userData));
return true;
}
return false;
}
function deleteUser(id) {
fetch("/api/users/" + id, {method: "DELETE"})
.then(res => res.json())
.then(data => alert("User deleted!"))
.catch(err => console.log(err));
}
$(document).ready(function(){
$(".delete-btn").click(function(){
deleteUser($(this).data("id"));
});
});
Your AI-Assisted Code Review:
Perform a comprehensive security and quality review of this code:
SECURITY ANALYSIS:
- Identify all security vulnerabilities
- Rate severity (Critical/High/Medium/Low)
- Provide specific exploit scenarios
- Recommend security fixes
CODE QUALITY REVIEW:
- Modern JavaScript best practices
- Error handling improvements
- Performance considerations
- Accessibility issues
- Maintainability concerns
ARCHITECTURAL IMPROVEMENTS:
- Suggest better patterns
- Recommend refactoring approach
- Consider scalability issues
- Address technical debt
PROVIDE:
1. Line-by-line issue analysis
2. Priority-ranked fix recommendations
3. Refactored code implementation
4. Prevention strategies for similar issues
Rate your confidence (1-5 stars) on each advanced skill:
Advanced Skill | Confidence |
---|---|
Multi-file refactoring with AI | ⭐⭐⭐⭐⭐ |
AI-powered debugging techniques | ⭐⭐⭐⭐⭐ |
Complex application architecture | ⭐⭐⭐⭐⭐ |
Performance optimization | ⭐⭐⭐⭐⭐ |
Code review with AI assistance | ⭐⭐⭐⭐⭐ |
Security vulnerability analysis | ⭐⭐⭐⭐⭐ |
Architectural pattern implementation | ⭐⭐⭐⭐⭐ |
You've mastered the advanced features that separate professional AI developers from beginners. You can now:
You're now in the top 10% of AI-powered developers!
Next: Learn how to share these superpowers with your team through collaboration techniques.