Week 6 - Advanced topics

Synchronous File IO

File processing

Error handling

Array methods

Closures

Style - How to write meaningful comments

Practice

Assignment

Core program

Content

Let’s get practical

Exercise 1: Contact Book (File I/O)

Build a simple contact management system using files.

Requirements:

  1. Create functions to manage contacts.txt:
  2. Test by adding 5 contacts, listing them, and searching for one
  3. Handle case where file doesn't exist (create it)

Challenge: Create deleteContact(name) that removes a contact and rewrites the file.

Exercise 2: Safe JSON Config (Error Handling)

Write robust configuration file handling with proper error management.

Requirements:

  1. Create loadConfig(filename) that:
  2. Create saveConfig(filename, config) with error handling
  3. Test with: missing file, corrupted JSON, and valid file

Challenge: Add validation that throws errors for invalid config values before saving.

Exercise 3: Product Filter Pipeline (Array Methods)

Process product data using chained array methods.

Requirements:

  1. Start with array of 10 products: {name, price, category, rating, inStock}
  2. Chain methods to:
  3. Calculate average price of filtered products using reduce()

Bonus: Use every() to check if all remaining products are under €100.

Exercise 4: Student Grade Analysis (Array Methods)

Analyze student performance data.

Requirements:

  1. Create array of students: {name, grades: [85, 92, 78, ...]}
  2. Use map() to add average property to each student
  3. Use filter() to find students with average > 80
  4. Use find() to locate student with highest average
  5. Use some() to check if any student failed (average < 60)
  6. Use reduce() to calculate class average

Challenge: Sort students by average and use forEach() to print rankings.

Exercise 5: Array Method Mastery (Array Methods)

Practice all array methods with a single dataset.

Requirements:

  1. Start with: [12, 5, 8, 130, 44, 3, 88, 22]
  2. Use filter() to get numbers > 10
  3. Use map() to double each number
  4. Use sort() to order ascending
  5. Use find() to get first number > 100
  6. Use every() to check if all are positive
  7. Use reduce() to sum all numbers

Challenge: Create your own array and apply at least 5 different methods in a meaningful chain.

Exercise 6: Private Counter Factory (Closures)

Build counter objects with private state using closures.

Requirements:

  1. Create createCounter(start, step) that returns object with:
  2. The count variable must be private (not accessible outside)
  3. Create 3 different counters with different configurations
  4. Demonstrate they maintain independent state

Challenge: Add getHistory() that returns array of all values the counter has had (use closure to track).


CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*

Found a mistake or have a suggestion? Let us know in the feedback form.