JavaScript and TypeScript course Β· Module 5: Advanced JavaScript
Implementing an Application Using Learned Techniques
In this lesson4
Welcome to the final phase of our Jurassic Park adventure! In this exercise we'll combine all the techniques we've learned so far to create a complete application for monitoring and managing the Jurassic Park ecosystem. This is our "grand finale" before moving on to structuring larger projects.
Project Goal
We'll create the "JurassicTracker" application - a system for monitoring, tracking, and managing dinosaurs in the park. Our application will use:
- Modular code (ES Modules)
- Asynchronous operations (Promises, async/await)
- Error handling (try/catch, custom error classes)
- Background services (setInterval)
- Application state management
Project Structure
Before we start implementing, let's plan the structure:
jurassic-tracker/
βββ index.js # Main application file
βββ modules/
β βββ api.js # API communication module
β βββ dinosaurs.js # Dinosaur management module
β βββ enclosures.js # Enclosure management module
β βββ security.js # Security systems module
β βββ monitoring.js # Park monitoring module
β βββ utils.js # Utility tools
β βββ errors/ # Error class directory
β βββ index.js # Exports all errors
β βββ APIError.js # API-related errors
β βββ DinoError.js # Dinosaur-related errors
β βββ SecurityError.js # Security-related errors
βββ data/
βββ config.js # Application configurationModule Implementations
Let's implement each of the modules. Remember that in practice these files would live in separate files according to the above structure.
1. Errors Module (errors/index.js)
First let's define our custom error classes:
// errors/APIError.js
export class APIError extends Error {
constructor(message, statusCode, endpoint) {
super(message);
this.name = 'APIError';
this.statusCode = statusCode;
this.endpoint = endpoint;
this.timestamp = new Date();
}
isServerError() {
return this.statusCode >= 500;
}
isClientError() {
return this.statusCode >= 400 && this.statusCode < 500;
}
}
// errors/DinoError.js
export class DinoError extends Error {
constructor(message, dinoId, species) {
super(message);
this.name = 'DinoError';
this.dinoId = dinoId;
this.species = species;
this.timestamp = new Date();
}
}
export class DinoNotFoundError extends DinoError {
constructor(dinoId) {
super(`Dinosaur with ID ${dinoId} was not found`, dinoId, null);
this.name = 'DinoNotFoundError';
}
}
export class DinoBehaviorError extends DinoError {
constructor(message, dinoId, species, behaviorType, dangerLevel) {
super(message, dinoId, species);
this.name = 'DinoBehaviorError';
this.behaviorType = behaviorType;
this.dangerLevel = dangerLevel; // 1-10
}
requiresIntervention() {
return this.dangerLevel >= 7;
}
}
// errors/SecurityError.js
export class SecurityError extends Error {
constructor(message, sector, systemType) {
super(message);
this.name = 'SecurityError';
this.sector = sector;
this.systemType = systemType;
this.timestamp = new Date();
}
}
export class EnclosureBreachError extends SecurityError {
constructor(sector, dinoSpecies, count) {
super(`Enclosure breach in sector ${sector}: ${count} ${dinoSpecies} specimens`, sector, 'enclosure');
this.name = 'EnclosureBreachError';
this.dinoSpecies = dinoSpecies;
this.count = count;
}
}
// errors/index.js
export * from './APIError.js';
export * from './DinoError.js';
export * from './SecurityError.js';2. API Module (api.js)
Our API module handles communication with the (hypothetical) Jurassic Park server:
// modules/api.js
import { APIError } from '../errors/index.js';
const API_DELAY = 500; // ms - simulate network delay
const API_ERROR_RATE = 0.1; // 10% chance of API error for realism
// Simulated dinosaur database
let dinosaursData = [
{ id: 'trx1', name: 'Rex', species: 'Tyrannosaurus', enclosureId: 'enc1', health: 98, lastFed: new Date(Date.now() - 3600000), behavior: 'calm' },
{ id: 'rap1', name: 'Blue', species: 'Velociraptor', enclosureId: 'enc2', health: 95, lastFed: new Date(Date.now() - 7200000), behavior: 'agitated' },
{ id: 'rap2', name: 'Delta', species: 'Velociraptor', enclosureId: 'enc2', health: 92, lastFed: new Date(Date.now() - 7200000), behavior: 'hunting' },
{ id: 'tri1', name: 'Sarah', species: 'Triceratops', enclosureId: 'enc3', health: 88, lastFed: new Date(Date.now() - 1800000), behavior: 'sleeping' },
{ id: 'bro1', name: 'Bronty', species: 'Brontosaurus', enclosureId: 'enc4', health: 100, lastFed: new Date(Date.now() - 900000), behavior: 'grazing' },
];
// Helper function simulating network delay
const simulateNetworkDelay = () => {
return new Promise(resolve => setTimeout(resolve, API_DELAY * (0.5 + Math.random())));
};
// Helper function simulating API errors
const simulateApiError = (endpoint) => {
if (Math.random() < API_ERROR_RATE) {
const errorTypes = [
{ statusCode: 500, message: 'Internal Server Error' },
{ statusCode: 503, message: 'Service Unavailable' },
{ statusCode: 429, message: 'Too Many Requests' },
{ statusCode: 403, message: 'Forbidden - Insufficient permissions' }
];
const errorType = errorTypes[Math.floor(Math.random() * errorTypes.length)];
throw new APIError(`API Error: ${errorType.message}`, errorType.statusCode, endpoint);
}
};
// API for fetching dinosaur data
export async function getDinosaurs() {
const endpoint = '/api/dinosaurs';
try {
await simulateNetworkDelay();
simulateApiError(endpoint);
return [...dinosaursData]; // Return a copy to avoid mutation
} catch (error) {
if (error instanceof APIError) throw error;
throw new APIError('Error fetching dinosaur data', 500, endpoint);
}
}
export async function getDinosaurById(id) {
const endpoint = `/api/dinosaurs/${id}`;
try {
await simulateNetworkDelay();
simulateApiError(endpoint);
const dino = dinosaursData.find(d => d.id === id);
if (!dino) {
throw new APIError(`Dinosaur with ID ${id} not found`, 404, endpoint);
}
return { ...dino };
} catch (error) {
if (error instanceof APIError) throw error;
throw new APIError('Error fetching dinosaur', 500, endpoint);
}
}3. Dinosaur Module (dinosaurs.js)
This module manages dinosaur data and behavior:
// modules/dinosaurs.js
import { getDinosaurs, getDinosaurById, updateDinosaur, logEvent } from './api.js';
import { DinoNotFoundError, DinoBehaviorError } from '../errors/index.js';
// Assess dinosaur behavior risk
function assessBehaviorRisk(dino) {
const dangerousSpecies = ['Tyrannosaurus', 'Velociraptor', 'Spinosaurus'];
const riskBehaviors = {
'calm': 1,
'grazing': 1,
'sleeping': 2,
'exploring': 4,
'agitated': 6,
'hunting': 7,
'aggressive': 9
};
// Base risk depends on species
let baseRisk = dangerousSpecies.includes(dino.species) ? 5 : 2;
// Risk modification based on behavior
const behaviorRisk = riskBehaviors[dino.behavior] || 3;
// Risk modification based on time since last feeding
const hoursSinceLastFed = (Date.now() - new Date(dino.lastFed).getTime()) / 3600000;
const hungerRisk = Math.min(5, Math.floor(hoursSinceLastFed / 3));
// Total risk level (1-10)
const totalRisk = Math.min(10, baseRisk + behaviorRisk + hungerRisk);
return {
risk: totalRisk,
factors: {
species: baseRisk,
behavior: behaviorRisk,
hunger: hungerRisk
}
};
}
// Get all dinosaurs
export async function getAllDinosaurs() {
try {
const dinosaurs = await getDinosaurs();
// Enrich data with risk assessment
return dinosaurs.map(dino => ({
...dino,
riskAssessment: assessBehaviorRisk(dino)
}));
} catch (error) {
console.error('Error fetching dinosaur list:', error);
throw error;
}
}
// Get a specific dinosaur by ID
export async function getDinosaur(id) {
try {
const dino = await getDinosaurById(id);
return {
...dino,
riskAssessment: assessBehaviorRisk(dino)
};
} catch (error) {
if (error.statusCode === 404) {
throw new DinoNotFoundError(id);
}
console.error(`Error fetching dinosaur ${id}:`, error);
throw error;
}
}
// Feed a dinosaur
export async function feedDinosaur(id) {
try {
const dino = await getDinosaur(id);
// Update dinosaur state
const updatedDino = await updateDinosaur(id, {
lastFed: new Date(),
health: Math.min(100, dino.health + 5),
behavior: 'calm' // Dinosaurs are calmer after feeding
});
// Log the event
await logEvent('FEEDING', {
dinoId: id,
species: dino.species,
name: dino.name,
previousFeedingTime: dino.lastFed
});
return {
...updatedDino,
riskAssessment: assessBehaviorRisk(updatedDino)
};
} catch (error) {
console.error(`Error feeding dinosaur ${id}:`, error);
throw error;
}
}
// Monitor dinosaur behavior
export async function monitorBehavior(id) {
try {
const dino = await getDinosaur(id);
const { risk, factors } = assessBehaviorRisk(dino);
// Check if behavior requires intervention
if (risk >= 8) {
const error = new DinoBehaviorError(
`Dangerous behavior from dinosaur ${dino.name}`,
id,
dino.species,
dino.behavior,
risk
);
// Log the high-risk event
await logEvent('HIGH_RISK_BEHAVIOR', {
dinoId: id,
species: dino.species,
name: dino.name,
behavior: dino.behavior,
risk,
factors
});
throw error;
}
// For medium risk, just log
if (risk >= 5) {
await logEvent('MEDIUM_RISK_BEHAVIOR', {
dinoId: id,
species: dino.species,
name: dino.name,
behavior: dino.behavior,
risk,
factors
});
}
return { dino, risk, factors };
} catch (error) {
if (error instanceof DinoBehaviorError) {
throw error; // Re-throw our custom error
}
console.error(`Error monitoring dinosaur ${id}:`, error);
throw error;
}
}
// Simulate behavior change (used by the monitoring module)
export async function simulateBehaviorChange() {
try {
const allDinos = await getAllDinosaurs();
const randomIndex = Math.floor(Math.random() * allDinos.length);
const targetDino = allDinos[randomIndex];
// Possible behaviors depending on species and last feeding
const carnivores = ['Tyrannosaurus', 'Velociraptor', 'Spinosaurus'];
let behaviorPool;
if (carnivores.includes(targetDino.species)) {
// Predators have higher chance of aggressive behavior
behaviorPool = ['calm', 'sleeping', 'exploring', 'agitated', 'hunting', 'aggressive'];
} else {
// Herbivores are generally calmer
behaviorPool = ['calm', 'grazing', 'sleeping', 'exploring', 'agitated'];
}
// Hungry dinosaurs are more aggressive
const hoursSinceLastFed = (Date.now() - new Date(targetDino.lastFed).getTime()) / 3600000;
if (hoursSinceLastFed > 8) {
if (carnivores.includes(targetDino.species)) {
behaviorPool = ['agitated', 'hunting', 'aggressive'];
} else {
behaviorPool = ['agitated', 'exploring'];
}
}
// Random behavior selection
const newBehavior = behaviorPool[Math.floor(Math.random() * behaviorPool.length)];
// Update dinosaur state
const updatedDino = await updateDinosaur(targetDino.id, {
behavior: newBehavior
});
await logEvent('BEHAVIOR_CHANGE', {
dinoId: targetDino.id,
species: targetDino.species,
name: targetDino.name,
previousBehavior: targetDino.behavior,
newBehavior
});
return {
...updatedDino,
riskAssessment: assessBehaviorRisk(updatedDino)
};
} catch (error) {
console.error('Error simulating behavior change:', error);
throw error;
}
}4. Enclosure Module (enclosures.js)
This module manages enclosures and their security status:
// modules/enclosures.js
import { getEnclosures, getEnclosureById, updateEnclosure, logEvent } from './api.js';
import { SecurityError, EnclosureBreachError } from '../errors/index.js';
import { getAllDinosaurs } from './dinosaurs.js';
// Assess enclosure security status
function assessSecurityStatus(enclosure, dinosaurs) {
// Check how many dinosaurs are in the enclosure
const enclosureDinosaurs = dinosaurs.filter(dino => dino.enclosureId === enclosure.id);
// Check for carnivores
const carnivores = enclosureDinosaurs.filter(dino =>
['Tyrannosaurus', 'Velociraptor', 'Spinosaurus'].includes(dino.species)
);
// Check total risk
const totalRisk = enclosureDinosaurs.reduce((sum, dino) =>
sum + (dino.riskAssessment ? dino.riskAssessment.risk : 3), 0);
// Power status
const powerStatus = enclosure.powerStatus === 'active' ? 10 :
enclosure.powerStatus === 'backup' ? 5 : 0;
// Time since last inspection (in days)
const daysSinceInspection = (Date.now() - new Date(enclosure.lastInspection).getTime()) / (24 * 3600000);
const inspectionScore = daysSinceInspection < 1 ? 10 :
daysSinceInspection < 3 ? 7 :
daysSinceInspection < 7 ? 4 : 1;
// Calculate overall security score (0-100)
const securityScore = Math.max(0, Math.min(100,
enclosure.securityLevel * 10 - totalRisk + powerStatus + inspectionScore
));
return {
id: enclosure.id,
name: enclosure.name,
sector: enclosure.sector,
dinosaurCount: enclosureDinosaurs.length,
carnivoreCount: carnivores.length,
securityLevel: enclosure.securityLevel,
powerStatus: enclosure.powerStatus,
securityScore,
status: securityScore >= 80 ? 'secure' :
securityScore >= 60 ? 'normal' :
securityScore >= 40 ? 'warning' : 'danger',
dinosaurs: enclosureDinosaurs.map(d => ({
id: d.id,
name: d.name,
species: d.species,
risk: d.riskAssessment ? d.riskAssessment.risk : 3
}))
};
}
// Get all enclosures with security assessment
export async function getAllEnclosures() {
try {
const [enclosures, dinosaurs] = await Promise.all([
getEnclosures(),
getAllDinosaurs()
]);
// Enrich data with security assessment
return enclosures.map(enclosure =>
assessSecurityStatus(enclosure, dinosaurs)
);
} catch (error) {
console.error('Error fetching enclosure list:', error);
throw error;
}
}
// Inspect an enclosure
export async function inspectEnclosure(id) {
try {
const enclosure = await getEnclosureById(id);
// Update last inspection date
const updatedEnclosure = await updateEnclosure(id, {
lastInspection: new Date()
});
// Log the event
await logEvent('ENCLOSURE_INSPECTION', {
enclosureId: id,
name: enclosure.name,
sector: enclosure.sector,
previousInspection: enclosure.lastInspection
});
// Fetch dinosaurs to update security assessment
const dinosaurs = await getAllDinosaurs();
return assessSecurityStatus(updatedEnclosure, dinosaurs);
} catch (error) {
console.error(`Error inspecting enclosure ${id}:`, error);
throw error;
}
}
// Simulate power failure
export async function simulatePowerFailure() {
try {
const enclosures = await getEnclosures();
// Select a random enclosure
const randomIndex = Math.floor(Math.random() * enclosures.length);
const targetEnclosure = enclosures[randomIndex];
if (targetEnclosure.powerStatus !== 'active') return;
// 70% chance of backup power, 30% chance of total failure
const newPowerStatus = Math.random() < 0.7 ? 'backup' : 'failure';
// Update enclosure state
const updatedEnclosure = await updateEnclosure(targetEnclosure.id, {
powerStatus: newPowerStatus
});
await logEvent('POWER_FAILURE', {
enclosureId: targetEnclosure.id,
name: targetEnclosure.name,
sector: targetEnclosure.sector,
powerStatus: newPowerStatus
});
// Check if failure could lead to an enclosure breach
if (newPowerStatus === 'failure') {
const dinosaurs = await getAllDinosaurs();
const enclosureDinos = dinosaurs.filter(dino => dino.enclosureId === targetEnclosure.id);
const dangerousSpecies = ['Tyrannosaurus', 'Velociraptor', 'Spinosaurus'];
const hasDangerousDinos = enclosureDinos.some(dino =>
dangerousSpecies.includes(dino.species)
);
if (hasDangerousDinos && targetEnclosure.securityLevel >= 8) {
const breachingSpecies = enclosureDinos.find(dino =>
dangerousSpecies.includes(dino.species)
).species;
const breachingCount = enclosureDinos.filter(dino =>
dino.species === breachingSpecies
).length;
throw new EnclosureBreachError(
targetEnclosure.sector,
breachingSpecies,
breachingCount
);
}
}
const dinosaurs = await getAllDinosaurs();
return assessSecurityStatus(updatedEnclosure, dinosaurs);
} catch (error) {
if (error instanceof EnclosureBreachError) {
await logEvent('ENCLOSURE_BREACH', {
sector: error.sector,
species: error.dinoSpecies,
count: error.count,
timestamp: error.timestamp
});
throw error;
}
console.error('Error simulating power failure:', error);
throw error;
}
}
// Repair power system
export async function repairPowerSystem(id) {
try {
const enclosure = await getEnclosureById(id);
if (enclosure.powerStatus === 'active') {
throw new SecurityError(
'Power system is already active',
enclosure.sector,
'power'
);
}
// Update power status
const updatedEnclosure = await updateEnclosure(id, {
powerStatus: 'active'
});
await logEvent('POWER_RESTORED', {
enclosureId: id,
name: enclosure.name,
sector: enclosure.sector,
previousStatus: enclosure.powerStatus
});
const dinosaurs = await getAllDinosaurs();
return assessSecurityStatus(updatedEnclosure, dinosaurs);
} catch (error) {
console.error(`Error repairing power system for enclosure ${id}:`, error);
throw error;
}
}5. Utility Functions (utils.js)
// modules/utils.js
export function formatDate(date) {
return new Intl.DateTimeFormat('en-US', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit'
}).format(new Date(date));
}
export function formatTimeAgo(date) {
const diff = Date.now() - new Date(date).getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes} min ago`;
if (hours < 24) return `${hours} h ago`;
return `${Math.floor(hours / 24)} days ago`;
}
export async function retry(fn, maxAttempts = 3, delay = 1000) {
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt < maxAttempts) {
console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
export function memoize(fn) {
const cache = new Map();
return async function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = await fn(...args);
cache.set(key, result);
return result;
};
}6. Monitoring Module (monitoring.js)
// modules/monitoring.js
import { getDinosaurs } from './api.js';
import { DinoBehaviorError, EnclosureBreachError } from '../errors/index.js';
import { formatTimeAgo } from './utils.js';
class ParkMonitor {
constructor() {
this.intervals = [];
this.alertHandlers = [];
this.isRunning = false;
}
onAlert(handler) {
this.alertHandlers.push(handler);
return () => {
this.alertHandlers = this.alertHandlers.filter(h => h !== handler);
};
}
_fireAlert(alert) {
this.alertHandlers.forEach(handler => handler(alert));
}
async checkDinosaurStatuses() {
try {
const dinosaurs = await getDinosaurs();
for (const dino of dinosaurs) {
const hoursSinceFeeding = (Date.now() - new Date(dino.lastFed).getTime()) / 3600000;
if (hoursSinceFeeding > 8) {
this._fireAlert({
type: 'feeding',
severity: hoursSinceFeeding > 12 ? 'critical' : 'warning',
message: `${dino.name} hasn't been fed for ${formatTimeAgo(dino.lastFed)}`,
dinoId: dino.id
});
}
if (dino.behavior === 'escaped') {
this._fireAlert({
type: 'security',
severity: 'critical',
message: `BREACH: ${dino.name} (${dino.species}) has escaped!`,
dinoId: dino.id
});
}
}
} catch (error) {
console.error('Monitoring check failed:', error.message);
}
}
start(intervalMs = 30000) {
if (this.isRunning) return;
this.isRunning = true;
console.log('Park monitoring started');
const id = setInterval(() => {
this.checkDinosaurStatuses();
}, intervalMs);
this.intervals.push(id);
this.checkDinosaurStatuses(); // Run immediately
}
stop() {
this.intervals.forEach(id => clearInterval(id));
this.intervals = [];
this.isRunning = false;
console.log('Park monitoring stopped');
}
}
export const monitor = new ParkMonitor();7. Configuration (config.js)
Application configuration file:
// data/config.js
export const appConfig = {
// General application settings
appName: 'Jurassic Tracker',
version: '1.0.0',
// Monitoring settings
monitoring: {
dinoBehaviorInterval: 60000, // Dinosaur behavior monitoring interval (ms)
enclosureSecurityInterval: 90000, // Enclosure security monitoring interval (ms)
autoStart: true // Automatically start monitoring on startup
},
// API settings
api: {
baseUrl: 'https://jurassic-park-api.example.com', // In reality we'd use a real URL
timeout: 10000, // API request timeout (ms)
retryCount: 3 // Number of retry attempts for failed requests
},
// Dinosaur risk assessment
dinorisk: {
dangerousSpecies: ['Tyrannosaurus', 'Velociraptor', 'Spinosaurus', 'Allosaurus', 'Dilophosaurus'],
behaviorRiskMatrix: {
'calm': { base: 1, factor: 0.8 },
'grazing': { base: 1, factor: 0.9 },
'sleeping': { base: 2, factor: 0.7 },
'exploring': { base: 4, factor: 1.0 },
'agitated': { base: 6, factor: 1.2 },
'hunting': { base: 7, factor: 1.5 },
'aggressive': { base: 9, factor: 2.0 }
},
hungerRiskHours: 3, // Hours after which hunger starts affecting risk
hungerRiskFactor: 0.5 // Hunger impact factor on risk
},
// Security levels for notifications
security: {
alertThresholds: {
low: 3,
medium: 5,
high: 7,
critical: 9
},
autoResolveAlerts: false // Whether to automatically mark alerts as resolved
}
};
export default appConfig;8. Main Application File (index.js)
// index.js
import { getDinosaurs } from './modules/api.js';
import { monitor } from './modules/monitoring.js';
import { retry } from './modules/utils.js';
async function initialize() {
console.log('=== JurassicTracker Starting ===');
// Set up alert handling
const unsubAlert = monitor.onAlert((alert) => {
const icon = alert.severity === 'critical' ? '!!' : '!';
console.log(`${icon} [${alert.type.toUpperCase()}] ${alert.message}`);
});
try {
// Fetch initial data with retry logic
const dinosaurs = await retry(() => getDinosaurs(), 3, 1000);
console.log(`Loaded ${dinosaurs.length} dinosaurs`);
// Start background monitoring
monitor.start(10000); // Check every 10 seconds
console.log('=== JurassicTracker Ready ===');
// Cleanup on shutdown
const cleanup = () => {
monitor.stop();
unsubAlert();
console.log('JurassicTracker shut down gracefully');
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
} catch (error) {
console.error('Fatal initialization error:', error.message);
process.exit(1);
}
}
initialize();Summary of Applied Techniques
In our JurassicTracker application we used all the most important techniques learned in this module:
- ES Modules - the entire app is organized into modules that import and export functionality
- Asynchrony:
- We use async/await for clean asynchronous operation handling
- We use Promise.all for parallel operation execution
- We handle delays and time intervals
- Error handling:
- We created a hierarchy of custom error classes (APIError, DinoError, SecurityError)
- We use try/catch blocks for local error handling
- We implement retry logic for operations that can be retried
- Background monitoring:
- We use setInterval for cyclical monitoring tasks
- We implement a notification system based on the Observer pattern
- Application state management:
- We store state in module variables
- We use Map for efficient data storage
- We implement memoization for optimization
This application shows how to combine all the learned techniques into a functional, modular, and fault-tolerant system.
In the next exercise we'll delve into structuring code in even larger JavaScript projects, extending the techniques and patterns we've learned.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the best practice for organizing modules in a JavaScript project?
Hands-on tasks in the game
- Code editor
Create a DinosaurDatabase with methods and a ParkMonitor with error handling.
- Vertical ordering
Order the project layers from lowest to highest: