1/5
Easy#featurejavascriptarrayssorting

Show the top scores on the results screen

sample/quiz-night#23 · @trivia-tam · MIT · licence

sample level · invented code, not a real repository

description
Adds topScores() for the new "Best rounds" box on the results screen (#21). It takes the score of every round, sorts them and returns the best five. Added a test with a mocked store.
2 commits · 2 files
  • 4e1c9a7feat: topScores for the results screen
  • b20f6d3test: topScores returns the best scores first

// files changed

Msrc/leaderboard.js+8−0
@@ -1,5 +1,13 @@
11import { loadRounds } from "./store.js";
22
33export function roundsPlayed() {
44 return loadRounds().length;
55}
6
7/** The best scores of all rounds, highest first. */
8export function topScores(limit = 5) {
9 const scores = loadRounds().map((round) => round.score);
10 scores.sort();
11 scores.reverse();
12 return scores.slice(0, limit);
13}
Atest/leaderboard.test.js+10−0
@@ -0,0 +1,10 @@
1import { expect, it, vi } from "vitest";
2import { topScores } from "../src/leaderboard.js";
3
4vi.mock("../src/store.js", () => ({
5 loadRounds: () => [{ score: 3 }, { score: 8 }, { score: 5 }],
6}));
7
8it("returns the best scores first", () => {
9 expect(topScores(2)).toEqual([8, 5]);
10});