The leaderboard that forgets who it skipped
A leaderboard in a quiz app · 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:
- Output is sorted by `score`, highest first; input order is kept among equal scores.
- `rank` starts at 1. Equal scores share the same rank.
- After a tie, the next rank accounts for every tied player: a player's rank is always one more than the number of players strictly ahead of them.
- `rankOf` returns that same rank for a single player, or `null` if the name is not on the board.
Review it before it ships to the weekly tournament page.
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();
});
});