← All exercises

The leaderboard that forgets who it skipped

A leaderboard in a quiz app · Logic · difficulty 2/3 · ~8 min

A teammate asked the AI assistant: "Write a rankPlayers(players) function for our quiz leaderboard. Sort by score, highest first, and attach a rank to each player. Use standard competition ranking: players with the same score share a rank, and the next distinct score gets the rank it would have in a plain numbered list (so 1, 2, 2, 4, not 1, 2, 2, 3). Also add a rankOf(players, name) helper for the profile page."

The code came back in under a minute, with passing tests. The contract promised by the docstring:

Review it before it ships to the weekly tournament page.

Repair the code until the hidden tests pass.

code.ts

Visible tests (they pass on the code as given)
import { describe, it, expect } from "@debunk/harness";
import { rankPlayers, rankOf } from "./code";

describe("rankPlayers", () => {
  it("sorts by score, highest first, and numbers the ranks", () => {
    const board = rankPlayers([
      { name: "mia", score: 40 },
      { name: "leo", score: 90 },
      { name: "sam", score: 65 },
    ]);
    expect(board.map((p) => p.name)).toEqual(["leo", "sam", "mia"]);
    expect(board.map((p) => p.rank)).toEqual([1, 2, 3]);
  });

  it("gives a single player rank 1", () => {
    expect(rankPlayers([{ name: "leo", score: 10 }])[0].rank).toBe(1);
  });

  it("rankOf finds a player's rank by name", () => {
    const players = [
      { name: "mia", score: 40 },
      { name: "leo", score: 90 },
    ];
    expect(rankOf(players, "mia")).toBe(2);
    expect(rankOf(players, "nobody")).toBeNull();
  });
});