Skip to content
HopperHopper

Course navigation

Phase 2 · Data and functionsDay 12

Checkpoint project 1

  • About 75 minutes
  • 9 sections
  • Runnable TypeScript examples

Before you start

About 75 minutes

By the end you will be able to

  1. Build a command-line grade book from a written brief, one working milestone at a time, with no step-by-step instructions.
  2. Model the data with a type alias and give each calculation its own typed function.
  3. Handle a student with no scores and an empty class without a crash, NaN, or a wrong grade.
  4. Check a finished program against its brief on purpose, including every edge case.

What to remember from earlier

Set up a day12 folder exactly as you set up day01 in 1.2: npm init -y, npm install --save-dev typescript, and the same tsconfig.json. Today has no new reading. You spend the whole hour building one program, grade-book.ts, using only what Days 1 to 11 taught.

Real programs combine many ideas at once, and the hard part is no longer “what does reduce do?” but “which tool fits this job, and in what order?” A checkpoint project is a program you build to find out what you can already do on your own. It also shows you which earlier days need another look.

Plan for 10 minutes, build for 45, then spend the last 5 minutes rereading your code and renaming anything unclear. Work through the milestones in order: each one ends with a program that passes npx tsc and runs, so you always have something working to come back to. Type your own code. The reference solution is at the end, under Putting it together; open it only after your program passes the self-check in 12.8, or when you have been stuck on one milestone for more than 10 minutes.

Section 1 of 9

12.1 The Project Brief

A project brief is a short description of what a program must do, written before anyone writes code. It says what, not how. Here is today’s.

Build a command-line grade book.

  • The program starts from a hard-coded array of students: the data is typed into the program itself, because until Day 13 a program cannot read a file or what a person types. Each student has a name and a list of scores. Use at least four students, and give one of them no scores at all.
  • The data is modeled with a type alias: type Student = { name: string; scores: number[] }.
  • Each calculation is its own function with typed parameters and a typed return value: average(scores), letterGrade(average), highest(scores), lowest(scores), and classAverage(students).
  • The program prints a formatted report: a header, then one row per student with the name, average to one decimal place, letter grade, highest score, and lowest score, with the columns lined up; then a class summary with the number of students, the class average and its grade, and the top student.
  • Edge cases: a student with no scores has an average of 0 and a grade shown as – (a dash), and the program never prints NaN or Infinity. An empty class prints a message instead of a report.
  • Bonus, if there is time: sort the rows from the best average down, or add a “most improved” line.

An edge case is an input at the edge of what a program expects, such as an empty list or a single score, where code that works for ordinary input often goes wrong. The brief names two, and your program must handle both.

Here is the output of the finished program, so you can see the goal. The reference solution prints the sorted report, then an empty class:

Name     Avg  Grade  High   Low
-------------------------------
Ana     91.7      A    95    88
Elena   85.0      B    90    80
Ben     74.3      C    80    68
Chloe   56.3      F    62    49
Dev      0.0      –     –     –
-------------------------------
Students: 5 (1 with no scores)
Class average: 76.8 (C)
Top student: Ana (91.7)

No students in the class yet.

Your names, numbers, and column widths do not have to match. Your program does have to do everything in the brief.

Key idea

Read the whole brief before you write any code, and come back to it after each milestone. A program is finished when it does everything the brief asks, not when npx tsc stops reporting errors.

Section 2 of 9

12.2 Planning the Pieces

A brief lists what the program does. Before typing, turn each line of it into a piece of TypeScript you already know. Nothing below is new; each row names the day that taught it, so you know where to look if you get stuck.

The brief says… The TypeScript piece Taught on
A name and a list of scores A type alias: type Student = { name: string; scores: number[] } Day 7
A hard-coded array of students const students: Student[] = [ { name: "Ana", scores: [92, 88] }, … ] Days 6, 7
Each calculation is a function function average(scores: number[]): number { … } Day 8
Add up the scores scores.reduce((sum, score) => sum + score, 0) Day 11
The highest and lowest score Math.max(...scores) and Math.min(...scores) Day 10
A letter grade An if chain, narrowest condition first Day 4
One decimal place average.toFixed(1) Day 3
Columns lined up padStart(width), after String() for a number Day 3
One row per student for (const student of students) Day 5
Only the students with scores students.filter((student) => student.scores.length > 0) Day 11
A student with no scores if (scores.length === 0) { return 0; } at the top of a function Days 4, 8
Bonus: rows from the best down students.toSorted((a, b) => average(b.scores) - average(a.scores)) Day 11
A doc comment on each function /** The mean of the scores, or 0 when there are none. */ Day 8

Two plan decisions matter more than the rest. First, functions calculate; one function prints. average, highest, lowest, and classAverage each take an array and return a number; none of them calls console.log. A function that returns a value can be used anywhere: in a row, in the summary, in a comparison for sorting, and, on Day 22, in a test. Only the function that prints the report talks to the terminal.

Second, decide what an empty array gives, and write it down in the doc comment. The type number[] includes the empty array, so every function that takes one will be called with one sooner or later. The brief says the average of no scores is 0, so average returns 0 for an empty array, and the report checks scores.length === 0 once to print the dash. Milestone 2 shows what happens when you forget.

Key idea

Give every calculation a function that returns a value and prints nothing, and decide what each one gives for an empty array before you write it. Then the report is just a loop that calls them.

Section 3 of 9

12.3 Milestone 1: The Students and Their Type

Goal: grade-book.ts declares the Student type and the array, and prints each student’s name with how many scores they have.

Start with the data, because every function takes it as input. Write the type alias first, then the array with its annotation, const students: Student[]. The annotation does two jobs: the checker rejects a student with a misspelled property or a score in quotes, and VS Code offers the property names as you type. Give one student an empty scores array; that is the edge case you will test at every milestone from now on.

Then write a for...of loop that prints one line per student. Here is one way milestone 1 can look. Compare it with yours after you have written your own:

students.ts
type Student = { name: string; scores: number[] };

const students: Student[] = [
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Ben", scores: [75, 80, 68] },
  { name: "Chloe", scores: [58, 62, 49] },
  { name: "Dev", scores: [] },
  { name: "Elena", scores: [85, 90, 80] },
];

for (const student of students) {
  console.log(`${student.name}: ${student.scores.length} scores`);
}

npx tsc reports no errors, and node students.ts shows:

Ana: 3 scores
Ben: 3 scores
Chloe: 3 scores
Dev: 0 scores
Elena: 3 scores

Inside the loop, student is one object of type Student, so student.name is a string and student.scores is a number[]; hover over each to see the checker agree. Dev’s empty array has length 0, and the loop is happy with it, because an empty array is still an array.

Test it: change a score to "92" with quotes and run npx tsc. The checker reports Type 'string' is not assignable to type 'number', Day 1’s TS2322, pointing at the quoted score. Put it back before you go on.

Watch out

A type the checker never sees. const students = [ … ] with no annotation works, and the checker infers an array type from the objects. But it infers the type from what you typed, so a student written as { name: "Dev" } with no scores property silently widens the type to “objects that might not have scores,” and every later function has to deal with that. The annotation : Student[] makes the checker report the missing property instead. Annotate the array.

Section 4 of 9

12.4 Milestone 2: Average, Highest, and Lowest

Goal: three functions, average, highest, and lowest, that take a number[] and return a number, each with a doc comment, and a line that prints them for one student.

Write them above the loop. average adds up the scores with reduce, starting from 0, and divides by the length. highest and lowest spread the array into Math.max and Math.min. Here they are for Ana’s scores, before any edge-case handling:

student-numbers.ts
function average(scores: number[]): number {
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

function highest(scores: number[]): number {
  return Math.max(...scores);
}

function lowest(scores: number[]): number {
  return Math.min(...scores);
}

const anaScores: number[] = [92, 88, 95];
console.log(average(anaScores));
console.log(average(anaScores).toFixed(1));
console.log(highest(anaScores));
console.log(lowest(anaScores));
91.66666666666667
91.7
95
88

Line 2’s reduce starts sum at 0 and adds each score in turn: 0 + 92 is 92, 92 + 88 is 180, and 180 + 95 is 275. Line 3 divides 275 by 3 and returns the exact float. Line 16 shows why the report must use toFixed(1): nobody wants fourteen decimal places in a table. toFixed gives a string, so keep the number for arithmetic and comparisons, and convert only when you print.

Now the edge case. Call the same three expressions with an empty array:

empty-scores.ts
const noScores: number[] = [];
const total = noScores.reduce((sum, score) => sum + score, 0);
console.log(total);
console.log(total / noScores.length);
console.log(Math.max(...noScores));
console.log(Math.min(...noScores));
0
NaN
-Infinity
Infinity

npx tsc reports no errors: every line is well typed. But reduce over nothing gives the starting value, 0, and 0 / 0 is NaN, the not-a-number value from 2.10. Math.max() with no arguments gives -Infinity and Math.min() gives Infinity, because those are the only starting points from which any number counts as bigger or smaller. None of these is a type error, so the checker cannot save you: NaN has the type number. Without a guard, Dev’s row would read NaN F -Infinity Infinity, and letterGrade(NaN) gives F, because every comparison with NaN is false and the chain falls through to else.

The fix is a guard at the top of each function: if (scores.length === 0) { return 0; }, returning early as Day 8 taught, and a doc comment that says so, such as /** The mean of the scores, or 0 when there are none. */. Add the guard to all three functions now. Then print average, highest, and lowest for Dev as well as Ana.

Test it: npx tsc reports no errors, and the program prints real numbers for Ana and 0 three times for Dev.

Key idea

0 / 0 is NaN and Math.max() of nothing is -Infinity, and both have the type number, so the checker accepts them. Guard every function that takes an array with if (scores.length === 0) and return the value the brief asks for.

Pause and try

Question 1 · Tracing

Predict exactly what this program shows.

predict-average.ts
function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

console.log(average([70, 80]));
console.log(average([100]));
console.log(average([]));
console.log(average([1, 2]).toFixed(1));
console.log(average([90, 91]) >= 90);
Check your reasoning
75
100
0
1.5
true
  • Line 9: reduce gives 150, and 150 / 2 is 75.
  • Line 10: one score, so the total is 100 and 100 / 1 is 100.
  • Line 11: the guard on line 2 runs before reduce, so the function returns 0, not NaN.
  • Line 12: 3 / 2 is 1.5, and toFixed(1) gives the string "1.5", shown as 1.5.
  • Line 13: 181 / 2 is 90.5, and 90.5 >= 90 is true.

Reread 12.4 Milestone 2: Average, Highest, and Lowest if any line differed.

Question 2 · Multiple choice

scores is a number[] holding [9, 100, 25]. Which expression gives the highest score, 100, and passes npx tsc?

  1. Math.max(scores)
  2. Math.max(...scores)
  3. scores.sort()[scores.length - 1]
  4. scores.at(-1)
Check your reasoning

B. Math.max takes separate numbers, not an array, and the spread ...scores from Day 10 passes 9, 100, 25 as three arguments. The result is 100.

  • A is wrong: Math.max expects numbers, so the checker rejects an array with Argument of type 'number[]' is not assignable to parameter of type 'number'.
  • C is wrong: the checker accepts it, but Day 11 showed that the default sort compares as text, so the order is [100, 25, 9], and the last element is 9. It also changes scores in place.
  • D is wrong: at(-1) is the last score, 25, whatever the order, and its type is number | undefined.

Reread 12.4 Milestone 2: Average, Highest, and Lowest if you chose differently.

Section 5 of 9

12.5 Milestone 3: Letter Grades

Goal: a letterGrade(average: number): string function, and a line per student that prints the name, the average to one decimal place, and the grade.

The bands are the ones from Day 4’s grade practice: 90 and above is A, 80 up to 90 is B, 70 up to 80 is C, 60 up to 70 is D, and below 60 is F. An if chain from the highest band down needs only a lower limit on each rung, because the program only reaches average >= 80 when average >= 90 was already false. The final else catches everything below 60. Here is the function with its boundaries tested:

letter-grade.ts
function letterGrade(average: number): string {
  if (average >= 90) {
    return "A";
  } else if (average >= 80) {
    return "B";
  } else if (average >= 70) {
    return "C";
  } else if (average >= 60) {
    return "D";
  } else {
    return "F";
  }
}

console.log(letterGrade(90));
console.log(letterGrade(89.9));
console.log(letterGrade(74.3));
console.log(letterGrade(60));
console.log(letterGrade(59.5));
console.log(letterGrade(0));
A
B
C
D
F
F

Exactly 90 is an A because >= includes the boundary, and 89.9 is a B. The last line is the problem to notice: letterGrade(0) is F, so a student with no scores, whose average is 0, would be shown as failing. That is not what the brief says. The report, not letterGrade, decides: when student.scores.length === 0, print – instead of calling letterGrade at all. Milestone 4 does that inside the row.

Test it: your program prints every student’s name, average, and grade on one line, such as Ana 91.7 A, and Dev’s line shows 0.0 and –.

Pause and try

Question 3 · Debugging

A classmate’s letterGrade leaves out the final else. npx tsc rejects it. Predict the message, explain what the checker is worried about, and write the fix.

grade-no-else.ts
function letterGrade(average: number): string {
  if (average >= 90) {
    return "A";
  } else if (average >= 80) {
    return "B";
  } else if (average >= 70) {
    return "C";
  } else if (average >= 60) {
    return "D";
  }
}

console.log(letterGrade(85));
Check your reasoning
grade-no-else.ts:1:40 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

Column 40 is the return type, string. The function promises to return a string every time it is called, and the checker follows every path through the chain. For an average of 59, all four conditions are false, no return runs, and the function falls off its closing } with no value, which in JavaScript means it returns undefined. undefined is not a string, so the promise is broken on that path, and the checker says so before the program ever runs. The fix is a final else that returns "F", as in letter-grade.ts. (Returning "F" after the chain, with no else, is also accepted, because then every path reaches a return.) If you typed the broken file, fix or delete it before your next check.

Reread 12.5 Milestone 3: Letter Grades if you missed the path with no return.

Section 6 of 9

12.6 Milestone 4: Aligned Report Rows

Goal: a header line, then one row per student with five columns lined up: name, average, grade, highest, lowest.

Columns line up when every row has the same width, and Day 3’s receipt practice showed how: pad each value with padStart(width) to a fixed width, and for the column after the name, work the width out from the name’s length so that the name’s column and the average together always take the same number of characters. padStart is a string method, so a number such as the highest score goes through String() first, and the average goes through toFixed(1), which already gives a string.

report-row.ts
const name: string = "Chloe";
const avg: string = (56.333).toFixed(1);
const grade: string = "F";
console.log(`Name${"Avg".padStart(8)}${"Grade".padStart(7)}`);
console.log(`${name}${avg.padStart(12 - name.length)}${grade.padStart(7)}`);
console.log(`Ana${"91.7".padStart(12 - "Ana".length)}${"A".padStart(7)}`);
Name     Avg  Grade
Chloe   56.3      F
Ana     91.7      A

On line 5, "Chloe" takes 5 characters, so avg is padded to 12 - 5 = 7, and the two together make 12. On line 6, "Ana" takes 3, so "91.7" is padded to 9: again 12. Each grade is then padded to 7, so the A and the F land under the e of Grade, which is padded to the same 7 in the header on line 4. Whatever the name, every row is 19 characters wide.

Write a reportRow(student: Student): string function that returns one row, and let the loop print what it returns. The function is the right place for the no-scores check from milestone 3: when student.scores.length === 0, return a row with 0.0 and dashes, and otherwise call average, letterGrade, highest, and lowest. The report rows then read like the finished output in 12.1.

Test it: print the header and all five rows. Every column’s right edge is straight, including Dev’s dashes and the two-digit scores.

Watch out

Padding a number. average(student.scores).padStart(7) is Day 3’s TS2339: Property 'padStart' does not exist on type 'number'. Call toFixed(1) first, which gives a string, and use String(highest(student.scores)) for the whole-number columns.

A name longer than the column. padStart never cuts a string short, and "Maximilian".padStart(12 - 10) asks for a width of 2, so a long name simply pushes its row to the right. With hard-coded data you can choose a width that fits your longest name; a program that reads names from a file (Day 13) would work the width out from the longest one.

Pause and try

Question 4 · Tracing

Predict exactly what this program shows, including every space. The | characters mark where each padded value starts and ends.

predict-row.ts
const name: string = "Ben";
const avg: number = 74.333;
const high: number = 80;
console.log(`|${name}${avg.toFixed(1).padStart(9 - name.length)}|${String(high).padStart(4)}|`);
console.log(`|${"Avg".padStart(6)}|${"High".padStart(4)}|`);
Check your reasoning
|Ben  74.3|  80|
|   Avg|High|
  • Line 4: "Ben" is 3 characters, so toFixed(1) gives "74.3" and padStart(9 - 3) pads it to 6: two spaces, then 74.3. Together with the name that is 9 characters. String(80) is "80", and padStart(4) adds two spaces.
  • Line 5: "Avg" is padded to 6 with three spaces, and "High" is already 4 characters, so padStart(4) leaves it unchanged.

Reread 12.6 Milestone 4: Aligned Report Rows if any space differed.

Section 7 of 9

12.7 Milestone 5: The Class Summary

Goal: after the rows, a summary: how many students, how many of them have no scores, the class average with its grade, and the top student. The whole report comes from one printReport(students: Student[]): void function, and an empty class prints a message.

First decide what the class average is. This course defines it as the mean of the averages of the students who have scores. Dev has none, so Dev counts in Students: 5 but not in the class average; including a 0 for Dev would drag the class down for a student who was never graded. classAverage filters the students who have scores, maps each one to average(student.scores), and averages the result. Because average already returns 0 for an empty array, a class where nobody has scores gives 0 without a second guard:

class-summary.ts
type Student = { name: string; scores: number[] };

function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

function classAverage(students: Student[]): number {
  const averages = students
    .filter((student) => student.scores.length > 0)
    .map((student) => average(student.scores));
  return average(averages);
}

const students: Student[] = [
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Dev", scores: [] },
  { name: "Elena", scores: [85, 90, 80] },
];
console.log(classAverage(students).toFixed(1));
console.log(classAverage([]));
console.log(classAverage([{ name: "Dev", scores: [] }]));
88.3
0
0

Line 23 averages Ana’s 91.67 and Elena’s 85 and gets 88.33. Lines 24 and 25 are the two empty cases: no students, and one student with no scores. Both give 0, and neither gives NaN.

Now move the printing into printReport. Its first lines handle the empty class: if (students.length === 0), print No students in the class yet. and return. Then print the header and the rows, then the summary. For the top student, you need the student with the highest average; the bonus in 12.9 sorts the array, and the first element of the sorted copy is the top student. Without the bonus, a for...of loop that remembers the best student so far, Day 5’s maximum pattern, does the same job.

When every student has no scores, there is no class average to report and no top student, so print No scores recorded yet. and return before those two lines.

Test it: call printReport(students) at the bottom, then printReport([]) to see the empty-class message. Change Dev’s array to [100] and the top student changes; change it back.

Pause and try

Question 5 · Short answer

Mira defines the class average differently: the mean of every score in the class, not the mean of the student averages. Ana has one score, [100], and Ben has three, [60, 60, 60]. Work out what each definition gives, and explain in one sentence why they differ.

Check your reasoning

The mean of the averages is (100 + 60) / 2 = 80. The mean of every score is (100 + 60 + 60 + 60) / 4 = 70.

two-averages.ts
function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

const ana: number[] = [100];
const ben: number[] = [60, 60, 60];
console.log(average([average(ana), average(ben)]));
console.log(average([...ana, ...ben]));
80
70

They differ because Mira’s definition counts Ben three times and Ana once: a student with more scores pulls the class average towards their own. The mean of the averages gives every student the same weight, whatever the number of scores. Neither is wrong, but the brief has to pick one, and the doc comment on classAverage should say which.

A complete answer gives 80 and 70 and says that the second definition weights students by how many scores they have.

Reread 12.7 Milestone 5: The Class Summary if your numbers differed.

Section 8 of 9

12.8 Milestone 6: Self-Check

Goal: prove your program meets the brief by checking every requirement and every edge case on purpose.

A program can look finished while one path, such as the empty class, still prints NaN. The only way to know is to try each path. Run npx tsc, then node grade-book.ts, and compare with the “Should happen” column. Write down anything that does not match.

Try Should happen
npx tsc Prints nothing (fix or delete any broken file first)
node grade-book.ts A header, one row per student, a summary
Look at the rows Every column’s right edge is straight
Look at the no-scores student’s row 0.0 and dashes, never NaN, Infinity, or F
Check one average by hand Matches the row to one decimal place
Check a grade exactly on a boundary, such as 80 B, not C
Count the students The summary’s count includes the one with no scores
Check the class average by hand The mean of the graded students’ averages, to one decimal
Call printReport([]) No students in the class yet. and nothing else
Give every student an empty array Rows of dashes, then No scores recorded yet., nothing else
Search your file for console.log Only in printReport (and reportRow returns a string)

When every row matches, your project is complete. Tick each requirement of the brief:

  • A hard-coded Student[] array with at least four students, one with no scores. Reread
  • average, highest, and lowest return a number and return 0 for an empty array. Reread
  • letterGrade returns the right letter on every band and exactly on each boundary. Reread
  • The report has a header and one aligned row per student, with a dash for a student with no scores. Reread
  • The summary shows the number of students, the class average with its grade, and the top student. Reread
  • An empty class prints a message, and no path prints NaN or Infinity. Reread
  • Every function has a doc comment, and only printReport prints. Reread

Then compare your program with the reference solution below. Different names, widths, or structure are fine, as long as every row of the table matches.

Key idea

Test the edge cases on purpose: the empty array, the empty class, and the value exactly on a boundary. A path you never tried is a path you do not know works.

Section 9 of 9

12.9 Bonus: Sorting and Most Improved

Do this only if the self-check passes with time to spare.

Sort the report by average. Day 11’s toSorted takes a comparator and gives a sorted copy, leaving students in its hard-coded order. For “best average first,” the comparator subtracts a’s average from b’s: (a, b) => average(b.scores) - average(a.scores). A negative result puts a first, so a bigger a average comes first. Loop over the sorted copy instead of students, and the first element of the copy is the top student for the summary.

Most improved. The student whose last score is furthest above their first. Write an improvement(scores: number[]): number function that returns scores[scores.length - 1] - scores[0], with a guard that returns 0 for fewer than two scores, and sort a copy by it. Question 7 has one solution.

Pause and try

Question 6 · Debugging

Sam’s summary line should name the student with the best average, Ana. npx tsc accepts the program, but it names the wrong student. Predict what it shows, explain why, and write the fix.

top-student-bug.ts
type Student = { name: string; scores: number[] };

function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

const students: Student[] = [
  { name: "Ben", scores: [75, 80, 68] },
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Chloe", scores: [58, 62, 49] },
];

const byAverage = students.toSorted((a, b) => average(a.scores) - average(b.scores));
const top = byAverage[0];
console.log(`Top student: ${top.name} (${average(top.scores).toFixed(1)})`);
Check your reasoning
Top student: Chloe (56.3)

The comparator on line 17 is average(a.scores) - average(b.scores), which is negative when a’s average is smaller, so toSorted puts the smaller average first: the copy is in ascending order, and its first element is the lowest student, Chloe. The checker cannot catch this: both orders are a valid Student[]. Swap the two sides so that a bigger average comes first:

top-student-fixed.ts
type Student = { name: string; scores: number[] };

function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

const students: Student[] = [
  { name: "Ben", scores: [75, 80, 68] },
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Chloe", scores: [58, 62, 49] },
];

const byAverage = students.toSorted((a, b) => average(b.scores) - average(a.scores));
const top = byAverage[0];
console.log(`Top student: ${top.name} (${average(top.scores).toFixed(1)})`);
Top student: Ana (91.7)

(Another fix keeps the ascending comparator and takes the last element, byAverage[byAverage.length - 1], but then the report rows, if they use the same copy, run from worst to best.)

Reread 12.9 Bonus: Sorting and Most Improved if you missed the direction of the comparator.

Question 7 · Short answer

Most improved. Add a line that names the student whose last score is furthest above their first score, with the improvement as a number. A student with fewer than two scores has an improvement of 0. Print each student’s improvement too, so you can check the answer.

Check your reasoning

One possible solution:

most-improved.ts
type Student = { name: string; scores: number[] };

const students: Student[] = [
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Ben", scores: [75, 80, 68] },
  { name: "Chloe", scores: [58, 62, 71] },
  { name: "Dev", scores: [] },
  { name: "Elena", scores: [85] },
];

/** The change from a student's first score to their last, or 0 with fewer than two scores. */
function improvement(scores: number[]): number {
  if (scores.length < 2) {
    return 0;
  }
  return scores[scores.length - 1] - scores[0];
}

const byImprovement = students.toSorted((a, b) => improvement(b.scores) - improvement(a.scores));
const mostImproved = byImprovement[0];
console.log(`Most improved: ${mostImproved.name} (+${improvement(mostImproved.scores)})`);
for (const student of students) {
  console.log(`${student.name}: ${improvement(student.scores)}`);
}
Most improved: Chloe (+13)
Ana: 3
Ben: -7
Chloe: 13
Dev: 0
Elena: 0

improvement returns 0 for Dev (no scores) and Elena (one score) because of its guard; without it, scores[0] would be undefined for Dev and the subtraction would give NaN. For Chloe, 71 - 58 is 13. The comparator improvement(b.scores) - improvement(a.scores) sorts the biggest improvement first, as in question 6, so byImprovement[0] is Chloe. Ben’s improvement is negative: his last score is below his first.

Reread 12.9 Bonus: Sorting and Most Improved if your result differed.

Wrap-up · 1 of 4

Putting it together

Here is the complete reference solution, including the bonus sort. It is one correct way, not the only one. Before you type it, make sure npx tsc is clean in your day12 folder: fix or delete grade-no-else.ts if you typed it.

grade-book.ts
type Student = { name: string; scores: number[] };

const students: Student[] = [
  { name: "Ana", scores: [92, 88, 95] },
  { name: "Ben", scores: [75, 80, 68] },
  { name: "Chloe", scores: [58, 62, 49] },
  { name: "Dev", scores: [] },
  { name: "Elena", scores: [85, 90, 80] },
];

/** The mean of the scores, or 0 when there are none. */
function average(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  const total = scores.reduce((sum, score) => sum + score, 0);
  return total / scores.length;
}

/** The letter grade for an average: 90 and above is A, then B, C, D by tens, and below 60 is F. */
function letterGrade(average: number): string {
  if (average >= 90) {
    return "A";
  } else if (average >= 80) {
    return "B";
  } else if (average >= 70) {
    return "C";
  } else if (average >= 60) {
    return "D";
  } else {
    return "F";
  }
}

/** The largest score, or 0 when there are none. */
function highest(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  return Math.max(...scores);
}

/** The smallest score, or 0 when there are none. */
function lowest(scores: number[]): number {
  if (scores.length === 0) {
    return 0;
  }
  return Math.min(...scores);
}

/** The mean of the averages of the students who have scores, or 0 when nobody does. */
function classAverage(students: Student[]): number {
  const averages = students
    .filter((student) => student.scores.length > 0)
    .map((student) => average(student.scores));
  return average(averages);
}

/** One aligned report row: name, average, grade, highest and lowest score. */
function reportRow(student: Student): string {
  const name = student.name;
  if (student.scores.length === 0) {
    return `${name}${"0.0".padStart(12 - name.length)}${"–".padStart(7)}${"–".padStart(6)}${"–".padStart(6)}`;
  }
  const avg = average(student.scores).toFixed(1);
  const grade = letterGrade(average(student.scores));
  const high = String(highest(student.scores));
  const low = String(lowest(student.scores));
  return `${name}${avg.padStart(12 - name.length)}${grade.padStart(7)}${high.padStart(6)}${low.padStart(6)}`;
}

/** Print the whole report: a header, one row per student from the best average down, then a class summary. */
function printReport(students: Student[]): void {
  if (students.length === 0) {
    console.log("No students in the class yet.");
    return;
  }
  const byAverage = students.toSorted((a, b) => average(b.scores) - average(a.scores));
  console.log(`Name${"Avg".padStart(8)}${"Grade".padStart(7)}${"High".padStart(6)}${"Low".padStart(6)}`);
  console.log("-".repeat(31));
  for (const student of byAverage) {
    console.log(reportRow(student));
  }
  console.log("-".repeat(31));
  const graded = students.filter((student) => student.scores.length > 0);
  console.log(`Students: ${students.length} (${students.length - graded.length} with no scores)`);
  if (graded.length === 0) {
    console.log("No scores recorded yet.");
    return;
  }
  const classAvg = classAverage(students);
  console.log(`Class average: ${classAvg.toFixed(1)} (${letterGrade(classAvg)})`);
  const top = byAverage[0];
  console.log(`Top student: ${top.name} (${average(top.scores).toFixed(1)})`);
}

printReport(students);
console.log();
printReport([]);

npx tsc reports no errors, and node grade-book.ts shows:

Name     Avg  Grade  High   Low
-------------------------------
Ana     91.7      A    95    88
Elena   85.0      B    90    80
Ben     74.3      C    80    68
Chloe   56.3      F    62    49
Dev      0.0      –     –     –
-------------------------------
Students: 5 (1 with no scores)
Class average: 76.8 (C)
Top student: Ana (91.7)

No students in the class yet.

How the pieces fit:

Lines What they do Milestone
1–9 The Student type and the hard-coded array, with Dev’s empty scores 12.3
11–18 average guards the empty array, then reduce and divide 12.4
20–33 letterGrade: the if chain from the top band down, with a final else 12.5
35–49 highest and lowest guard the empty array, then spread into Math.max and Math.min 12.4
51–57 classAverage filters the graded students, maps to their averages, and reuses average 12.7
59–70 reportRow returns a dashed row for no scores, otherwise one aligned row 12.6
72–78 printReport returns early for an empty class, then sorts a copy by average 12.7, 12.9
79–84 The header, a divider from repeat, and one row per student in sorted order 12.6
85–94 The summary: the count, the No scores recorded yet. path, the class average, the top student 12.7
97–99 Two calls: the full class, then the empty class 12.8
  • Only printReport calls console.log. The five calculation functions return values, so the sort comparator on line 78 and the summary on lines 91 to 94 can reuse average and classAverage without printing anything extra. On Day 13 you move these functions into their own module, and this split is what makes the move easy.
  • byAverage on line 78 is a copy. students keeps its hard-coded order, so a second call to printReport(students) prints the same report.
  • Line 93 reads byAverage[0] only after line 74 has returned for an empty class, so the first element exists. The checker gives it the type Student either way, which is why the guard must come first.
Wrap-up · 2 of 4

Common mistakes

Mistake What happens Fix
No guard for an empty array NaN, -Infinity, and Infinity in the report; no type error if (scores.length === 0) { return 0; } first
letterGrade(0) for a student with no scores An F for someone who was never graded Check scores.length === 0 in the row and print –
An if chain with no final else TS2366: Function lacks ending return statement Add else { return "F"; }
Math.max(scores) Argument of type 'number[]' is not assignable to parameter… Math.max(...scores)
average(...).padStart(7) TS2339: Property 'padStart' does not exist on type 'number' toFixed(1) first; String() for whole numbers
(a, b) => average(a.scores) - average(b.scores) Ascending order: the top student is the lowest one average(b.scores) - average(a.scores)
students.sort(...) instead of toSorted The hard-coded array is reordered for the rest of the program toSorted gives a copy
Including no-score students in the class average Each one adds a 0, dragging the class down filter to the students with scores first
console.log inside average Numbers print in the middle of the table, and the sort prints too Return the value; print only in printReport
Wrap-up · 3 of 4

Go further

Day 12 has no new reading. If a milestone sent you back to an earlier day, the matching reference pages are a good second explanation: MDN: Array (the reduce, filter, map, and toSorted methods), MDN: String.prototype.padStart, and the TypeScript Handbook: Object Types for type aliases.

Wrap-up · 4 of 4

Reflection

Check each statement. If the answer is “not yet,” reread the linked milestone and the day it names. Then write one or two sentences in your notes file: which of Days 1 to 11 felt shaky while you built this? Reread that day before you start Day 13.

  • I can turn each line of a project brief into a piece of TypeScript I know. Reread
  • I can model data with a type alias and an annotated array, and say what the annotation catches. Reread
  • I can write a typed function that returns a value, and guard it against an empty array. Reread
  • I can explain why an if chain that returns needs a final else. Reread
  • I can line up columns with padStart, toFixed, and String. Reread
  • I can combine filter, map, and a function I wrote to compute a summary. Reread
  • I can check a finished program against its brief, including every edge case. Reread
  • I can sort a copy of an array with a comparator and say which direction it sorts. Reread