Week 5 - Problem solving methods

Problem solving

Basic algorithms

Big O notation

Logging

Debugging

Unit testing

AI

Practice

Assignment

Back to core program

Week 5 Assignment

Task 1

Count values above a threshold

You are given an array of numbers and a threshold value.

Write a function that returns how many numbers in the array are greater than the threshold.


Function Signature

function countAboveThreshold(numbers, threshold) {
  // Your code here
}

Requirements


Example Usage

countAboveThreshold([1,5,10,3],4)// returns 2
countAboveThreshold([7,8,9],10)// returns 0
countAboveThreshold([],5)// returns 0

Task 2

Write Unit Tests

Your task is to write unit tests for the function below using Vitest.

You must not change the function implementation.

Your job is to prove that it works correctly by writing meaningful test cases.


Function to Test

export function calculateAverage(numbers) {
  if (!Array.isArray(numbers)) {
    return null;
  }

  if (numbers.length === 0) {
    return null;
  }

  let sum = 0;

  for (const num of numbers) {
    if (typeof num !== "number") {
      return null;
    }
    sum += num;
  }

  return sum / numbers.length;
}

What the Function Does


Requirements

Your unit tests should:


Test Cases to Include

Make sure your tests cover at least the following scenarios:

  1. A normal case with valid numbers
  2. An array with a single number
  3. An empty array
  4. A non-array input
  5. An array containing a non-number value

Expected Outcome

By the end of this task, your test file should clearly demonstrate that:


Task 3

Debug and Fix the Logic

In this task, you will practice finding and fixing errors by debugging. The code below runs, but it does not behave as expected.


Problem

The function below is supposed to return the number of vowels in a string.


Function to Debug

function countVowels(text) {
  let count = 0;

  for (let i = 0; i <= text.length; i++) {
    if (
      text[i] === "a" ||
      text[i] === "e" ||
      text[i] === "i" ||
      text[i] === "o" ||
      text[i] === "u"
    ) {
      count++;
    }
  }

  return count;
}

Your Task

  1. Run the function with different inputs.
  2. Use the debugger to observe:
  3. Identify what is wrong with the logic.
  4. Fix the function so it works correctly.

Example Usage

countVowels("hello")// returns 2
countVowels("javascript")// returns 3
countVowels("")// returns 0

Things to think about


Expected Outcome