JavaScript and TypeScript course ยท Module 2: Functions, Arrays and Objects

Final Project: Dinosaur Monitoring System

8 min read ยท
In this lesson4

Welcome back to the Jurassic Park command center! In this module you have learned about functions, arrays, variable scope, hoisting, the this keyword, objects and prototypes. Now it is time to combine this knowledge into one integrated Dinosaur Monitoring System - the operational heart of the whole park.

Imagine a central console where the park operators track the location, health and behavior of every dinosaur in real time. Sensors placed all over the park send data that our system has to process, filter and analyze. Without an efficient monitoring system, the park would quickly spiral out of control - just like in the movie!

In this project you will build a complete system that uses arrow functions to process data, array methods to filter and transform it, higher-order functions for flexible logic, and objects to model the park's entities.

Project Goal

You will build a monitoring system that:

  • Stores dinosaur data in arrays of objects
  • Uses functions with different types of parameters (default, rest)
  • Uses arrow functions for concise code
  • Filters, maps and reduces data with array methods
  • Manages variable scope correctly
  • Uses objects with methods to model the system

Functional Requirements

1. Dinosaur Database - Arrays and Objects

The first step is to create the park's database. Each dinosaur is an object with properties, and the whole population is stored in an array.

// The park's dinosaur database
const dinosaurs = [
  {
    id: 1,
    name: "Rex",
    species: "Tyrannosaurus Rex",
    weight: 8500,
    diet: "carnivore",
    enclosure: "A-1",
    isHealthy: true,
    heartRate: 72,
    lastFed: "2024-03-15 08:00"
  },
  {
    id: 2,
    name: "Tricia",
    species: "Triceratops",
    weight: 6200,
    diet: "herbivore",
    enclosure: "B-3",
    isHealthy: true,
    heartRate: 55,
    lastFed: "2024-03-15 07:30"
  },
  {
    id: 3,
    name: "Blue",
    species: "Velociraptor",
    weight: 75,
    diet: "carnivore",
    enclosure: "C-2",
    isHealthy: false,
    heartRate: 110,
    lastFed: "2024-03-14 18:00"
  },
  {
    id: 4,
    name: "Dippy",
    species: "Diplodocus",
    weight: 12000,
    diet: "herbivore",
    enclosure: "D-1",
    isHealthy: true,
    heartRate: 40,
    lastFed: "2024-03-15 06:00"
  },
  {
    id: 5,
    name: "Spike",
    species: "Stegosaurus",
    weight: 3500,
    diet: "herbivore",
    enclosure: "B-2",
    isHealthy: true,
    heartRate: 48,
    lastFed: "2024-03-15 07:00"
  }
];

// Adding a new dinosaur to the database
const addDinosaur = (name, species, weight, diet, enclosure) => {
  const newId = dinosaurs.length + 1;
  const newDino = {
    id: newId,
    name,
    species,
    weight,
    diet,
    enclosure,
    isHealthy: true,
    heartRate: 60,
    lastFed: new Date().toISOString()
  };
  dinosaurs.push(newDino);
  console.log("Registered:", newDino.name, "(" + newDino.species + ")");
  return newDino;
};

addDinosaur("Echo", "Velociraptor", 68, "carnivore", "C-2");
console.log("Total number of dinosaurs:", dinosaurs.length);

2. Filtering and Analysis - Array Methods

The system must make it possible to filter the population quickly by various criteria. This is where you will use filter, map, reduce and find.

// Filtering predators with filter
const carnivores = dinosaurs.filter(dino => dino.diet === "carnivore");
console.log("Predators:", carnivores.map(d => d.name));

// Filtering sick dinosaurs
const unhealthyDinos = dinosaurs.filter(dino => !dino.isHealthy);
console.log("Need treatment:", unhealthyDinos.map(d => d.name));

// Mapping - creating a report with names and weights
const weightReport = dinosaurs.map(dino => {
  return {
    name: dino.name,
    weight: dino.weight,
    category: dino.weight > 5000 ? "heavy" : "light"
  };
});
console.log("Weight report:");
weightReport.forEach(entry => {
  console.log("  " + entry.name + ": " + entry.weight + " kg (" + entry.category + ")");
});

// Reducing - calculating the total weight of all dinosaurs
const totalWeight = dinosaurs.reduce((sum, dino) => sum + dino.weight, 0);
console.log("Total population weight:", totalWeight, "kg");

// Average weight
const avgWeight = totalWeight / dinosaurs.length;
console.log("Average weight:", Math.round(avgWeight), "kg");

// Finding the heaviest dinosaur
const heaviest = dinosaurs.reduce((max, dino) =>
  dino.weight > max.weight ? dino : max
);
console.log("Heaviest:", heaviest.name, "-", heaviest.weight, "kg");

// find - looking for a specific dinosaur
const blue = dinosaurs.find(dino => dino.name === "Blue");
console.log("Found:", blue ? blue.name + " in " + blue.enclosure : "not found");

// some and every - checking conditions
const allHealthy = dinosaurs.every(dino => dino.isHealthy);
const anyUnhealthy = dinosaurs.some(dino => !dino.isHealthy);
console.log("All healthy:", allHealthy);
console.log("Any sick dinosaurs:", anyUnhealthy);

3. Monitoring Functions - Parameters, Scope and this

The system needs a set of monitoring functions with different types of parameters. Pay attention to variable scope and to the difference between regular functions and arrow functions when it comes to this.

// Function with default parameters
function generateAlert(dinoName, alertType = "INFO", priority = "normal") {
  const timestamp = new Date().toLocaleTimeString();
  console.log("[" + timestamp + "] [" + alertType + "] [" + priority + "] " + dinoName);
}

generateAlert("Rex", "WARNING", "high");
generateAlert("Tricia"); // will use the default values
generateAlert("Blue", "DANGER"); // priority will be "normal"

// Function with a rest parameter - logging multiple events
const logEvents = (enclosure, ...events) => {
  console.log("Enclosure " + enclosure + " - logged " + events.length + " events:");
  events.forEach((event, index) => {
    console.log("  " + (index + 1) + ". " + event);
  });
};

logEvents("A-1", "Feeding at 8:00", "Veterinary check-up", "Physical activity");
logEvents("C-2", "Escape attempt!");

// Monitor object with methods - this in context
const enclosureMonitor = {
  sector: "A",
  alertCount: 0,

  // Traditional method - this points to the object
  checkFence: function() {
    this.alertCount++;
    console.log("Checking the fence of sector " + this.sector +
                " (alert #" + this.alertCount + ")");
  },

  // ES6 shorthand method
  getStatus() {
    return "Sector " + this.sector + " - " + this.alertCount + " alerts";
  }
};

enclosureMonitor.checkFence();
enclosureMonitor.checkFence();
console.log(enclosureMonitor.getStatus());

// Variable scope - block vs function
function monitorHeartRates() {
  const threshold = 100; // available in the whole function

  for (let i = 0; i < dinosaurs.length; i++) {
    const dino = dinosaurs[i]; // available only in this block
    if (dino.heartRate > threshold) {
      let pulseStatus = "ELEVATED"; // available only in this if
      console.log(dino.name + ": heart rate " + dino.heartRate + " - " + pulseStatus);
    }
  }

  // console.log(pulseStatus); // ERROR! pulseStatus does not exist outside the if block
  // console.log(dino);   // ERROR! dino does not exist outside the for loop
  console.log("Alert threshold:", threshold); // OK - threshold is in the function scope
}

monitorHeartRates();

4. Advanced Processing - Chaining Methods

In a real monitoring system we often need to combine many operations into a chain. Array methods are perfect for this.

// Method chain - security report
const securityReport = dinosaurs
  .filter(dino => dino.diet === "carnivore") // predators only
  .map(dino => ({                            // data transformation
    name: dino.name,
    enclosure: dino.enclosure,
    danger: dino.weight > 1000 ? "HIGH" : "MEDIUM"
  }))
  .sort((a, b) => a.name.localeCompare(b.name)); // sorting

console.log("=== SECURITY REPORT ===");
securityReport.forEach(entry => {
  console.log(entry.name + " [" + entry.enclosure + "] - threat: " + entry.danger);
});

// Grouping dinosaurs by diet with reduce
const groupedByDiet = dinosaurs.reduce((groups, dino) => {
  const key = dino.diet;
  if (!groups[key]) {
    groups[key] = [];
  }
  groups[key].push(dino.name);
  return groups;
}, {});

console.log("=== BREAKDOWN BY DIET ===");
console.log("Herbivores:", groupedByDiet.herbivore);
console.log("Carnivores:", groupedByDiet.carnivore);

// Higher-order function - creating filters
function createFilter(property, value) {
  return (dino) => dino[property] === value;
}

const isCarnivore = createFilter("diet", "carnivore");
const isInSectorB = createFilter("enclosure", "B-3");

const carnivoreDinos = dinosaurs.filter(isCarnivore);
const sectorBDinos = dinosaurs.filter(isInSectorB);

console.log("Carnivores:", carnivoreDinos.map(d => d.name));
console.log("Sector B-3:", sectorBDinos.map(d => d.name));

// Population statistics
const stats = {
  total: dinosaurs.length,
  healthy: dinosaurs.filter(d => d.isHealthy).length,
  unhealthy: dinosaurs.filter(d => !d.isHealthy).length,
  avgHeartRate: Math.round(
    dinosaurs.reduce((sum, d) => sum + d.heartRate, 0) / dinosaurs.length
  ),
  heaviest: dinosaurs.reduce((max, d) => d.weight > max.weight ? d : max).name,
  lightest: dinosaurs.reduce((min, d) => d.weight < min.weight ? d : min).name
};

console.log("=== POPULATION STATISTICS ===");
console.log("Total:", stats.total);
console.log("Healthy:", stats.healthy);
console.log("Sick:", stats.unhealthy);
console.log("Average heart rate:", stats.avgHeartRate, "bpm");
console.log("Heaviest:", stats.heaviest);
console.log("Lightest:", stats.lightest);

Implementation Tips

As you build your monitoring system, pay attention to:

  1. Arrow functions vs regular functions - use arrow functions for callbacks (filter, map, reduce) and regular functions for object methods that need this
  2. Default parameters - useful when we do not always have all the data (e.g. the alert priority)
  3. The rest parameter (...args) - ideal when the number of arguments varies (e.g. a list of events)
  4. Method chaining - filter().map().sort() is more readable than nested loops
  5. Variable scope - let and const have block scope, var has function scope - choose consciously
  6. Array methods and the original - filter and map create new arrays and reduce returns a new value, while push, splice and sort modify the original
  7. Objects as data structures - group related data into objects instead of keeping it in separate variables

Good Luck!

Time to step into the role of Jurassic Park's chief operator! Build your own Monitoring System in the editor below. Combine arrays, functions, array methods and objects into one working system. Remember - every dinosaur in the park depends on your code. As John Hammond used to say: "We spared no expense" - so don't spare any code either!

Code for this lesson: index.js
// Final project: Dinosaur monitoring system
// Combine: functions, arrays, arrow functions, scope, this, objects

// === 1. PARK DATABASE ===
const dinosaurs = [
  { id: 1, name: "Rex", species: "Tyrannosaurus", weight: 8500, diet: "carnivore", enclosure: "A-1", isHealthy: true, heartRate: 72 },
  { id: 2, name: "Tricia", species: "Triceratops", weight: 6200, diet: "herbivore", enclosure: "B-3", isHealthy: true, heartRate: 55 },
  { id: 3, name: "Blue", species: "Velociraptor", weight: 75, diet: "carnivore", enclosure: "C-2", isHealthy: false, heartRate: 110 },
];

// === 2. MONITORING SYSTEM ===
// TODO: Create a monitoringSystem object with methods using this
const monitoringSystem = {
  parkName: "Jurassic Park",
  alerts: [],

  // TODO: Method filtering dinosaurs by diet (use an arrow function)
  filterByDiet: (dinos, diet) => {
    // TODO: Use filter()
  },

  // TODO: Method generating a health report (use map)
  getHealthReport(dinos) {
    // TODO: Use map() to create a report for each dinosaur
    // Return an array of objects: { name, status, heartRate }
  },

  // TODO: Method calculating average weight (use reduce)
  calculateAverageWeight(dinos) {
    // TODO: Use reduce() to calculate the average
  },

  // TODO: Method adding an alert
  addAlert(message, severity) {
    // TODO: Add an alert with a timestamp to this.alerts
  },
};

// === 3. HIGHER-ORDER FUNCTIONS ===
// TODO: Create a function createFilter that returns a filtering function
function createFilter(property, value) {
  // TODO: Return an arrow function that filters by the given property
}

// === 4. FINAL REPORT ===
// TODO: Generate and display a full monitoring report
// - List of dinosaurs by diet
// - Health report
// - Average weight
// - Active alerts

console.log("Monitoring system started!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitLink - Park Control Systems
  2. VideoVideo: Module Summary

Useful articles