Problem Solving Fundamentals · Approaching a Problem

Check the edges

edge cases

Check the edges

A bridge is built for the traffic it will really meet, not only for one truck. Engineers test it empty, test it with a single truck, and test it backed up with a jam, because the extremes, not the average day, are where it fails. Functions fail the same way.

Take this task: return the average of a list of numbers. The obvious version adds them up and divides by how many there are:

function average(numbers) {
  return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
}

It looks right. Hand it [2, 4, 6] and it returns 4. Now hand it the empty list. There is nothing to add, and you divide by zero. The result is not 0; it is NaN, a quiet lie that spreads through everything it touches.

That is the edge the happy path hides. Before you call the function done, walk its inputs through the extremes: empty, one element, many, and a bad value. For the average, the empty list needs a decision, and the honest one is to return 0 and say why.

Add the guard before the sum:

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

The happy path was never the hard part. The edges are.

You are about to solve a Challenge on edge cases.

Challenge

A list of numbers arrives and you need its average. The one-line version adds them up and divides by the count, and it breaks the moment the list is empty, because there is nothing to sum and you divide by zero.

Export an average function from index.js. It takes an array of numbers and returns their mean. When the list is empty, return 0 rather than NaN, so the degenerate input has a defined answer.

index.js
export function average(numbers) {
  return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
}

export function render(mount) {
  const numbers = [];

  mount.textContent = String(average(numbers));
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.