Sort by what matters to you
By the end of this lesson you will have a watchlist you can sort by move, by volume or in your own order, a choice that survives a reload, and a test that proves tied rows hold still.
Your list is currently in the order you typed it. That is a real ordering and often the right one. Changing it is a decision with a trap underneath.
If you did Pair With Your Agent in the same clone, your page already orders rows by size of move, through a small function you wrote there. This lesson builds the general version, with three orders to choose from. When it works, the old function is redundant: ask the agent to remove it and its test, and to update any comment or line in the plan that still describes the page as ordered by move. Keep one meaning of "size of move" throughout: how far the price moved in per cent, up or down, so a -3% sorts before a +2%.
Ordering is an opinion
A watchlist sorted by "biggest mover" is not neutral. It puts whatever is loud today at the top and quietly suggests that is what deserves your attention. Sometimes that is exactly what you want. Sometimes the instrument that has not moved is the story, and a mover-sorted list buries it.
So decide deliberately, and know what each choice is telling you:
| Sort | What it surfaces | What it hides |
|---|---|---|
| As written | your own priority | today's outliers |
Size of move (change_p, up or down) |
what moved most | anything stable |
Absolute change (change) |
big-price names | small-price names that moved more |
| Volume | where the activity is | thin names doing something unusual |
Note the third row. Sorting by change rather than the percentage move change_p mostly sorts by share price: a 1% move on a 500-dollar stock beats a 5% move on a 20-dollar one. That is almost never what a person means by "biggest mover", and it is the sort of thing that looks fine until you notice the same three names are always on top.
Implement it as a pure function
type SortKey = "manual" | "change_p" | "volume";
function sortRows(rows: Quote[], key: SortKey, myOrder: string[]): Quote[] {
if (key === "manual") {
return myOrder
.map((code) => rows.find((r) => r.code === code))
.filter((r): r is Quote => Boolean(r));
}
const size = (r: Quote) => (key === "change_p" ? Math.abs(r.change_p) : r.volume ?? 0);
return [...rows].sort((a, b) => size(b) - size(a));
}
myOrder is your own list of tickers, the one in src/lib/watchlist.ts; it has nothing to do with ascending or descending.
Two details that matter more than they look.
[...rows] before .sort(). Array.prototype.sort mutates in place. Sorting the array you were handed changes it for everything else holding a reference, and produces bugs that only appear when a second component renders the same data. Copy first, always.
Manual order is rebuilt from your list, not from the response. The API does not promise to return rows in the order you asked. If you want your ordering, reconstruct it from WATCHLIST.
The tie-break trap
Ask your assistant for a sort and you will usually get exactly the comparator above, with no tie-break. It is fine, until two rows tie: two instruments both up 0.32%, or a market where nothing has moved yet and change_p is 0 for everything.
sort will not shuffle them. It has been stable since ES2019, so tied rows keep exactly the order they arrived in. That is the problem: the order they arrived in is the API's, and the API does not promise one. A fresh fetch can hand you the same two rows the other way round, and your faithfully-stable sort will faithfully preserve that. A list that reorders itself while you look at it is worse than an unsorted one, because you stop trusting the whole screen.
Break the tie explicitly:
return [...rows].sort((a, b) => size(b) - size(a) || a.code.localeCompare(b.code));
That second comparison is the entire fix, and it is the kind of thing you only put in if you have thought about ties — two names up exactly 0.32%, or a row of thinly traded names that all last printed at the same price.
Persist the choice, or do not offer it
A sort control that resets on every reload is an irritation. Keep it in localStorage alongside the list, or leave the feature out. Half-built preferences are worse than no preferences: they teach the user their input does not stick.
Try it now
The prompt
Mock mode on, plan mode on, and paste:
Add sorting to the watchlist with three orders: my own order from
src/lib/watchlist.ts (the default), size of move (the absolute value
of change_p, biggest first, so -3 comes before +2), and volume, biggest
first. Put it in a pure function sortRows(rows, key, myOrder) in
src/lib/sort.ts, where myOrder is the list of tickers from
src/lib/watchlist.ts, and add a small control that keeps the choice in
localStorage. If the page already has an earlier function that orders
by size of move, replace it with this one and delete it and its test.
Update any comment that still describes the old ordering. The page stays a server component: the control
and the sorted table are one small "use client" island that receives
the rows as props and never fetches. Unavailable rows go last. Plan
first and name the files. Write tests/sort.test.ts before the code: the
input array is not mutated, my order comes from my list rather than
from the response, a -3 move comes before a +2 move, and two rows tied
on size of move come out in the same order whichever order they arrive
in. Show me them failing, then write
the code. No new request. Run npm test and npm run check:leak.
A good answer adds src/lib/sort.ts, the test file and one client component, changes the line or two of src/app/page.tsx that render the table, and shows the tests red before the code. The tie test turns green only once the comparator has a tie-break; the Break step below shows it going red again.
Check it yourself
- The first test run was red, with the tie test among the failures.
- The second run is green, and every earlier test still passes.
- In mock mode, switch between the three orders and reload: the choice sticks.
grep -rln "use client" srclists the new island and nothing else;src/app/page.tsxis not on it.npm run check:leakpasses: the island receives rows, never a key.
Break it on purpose
Then test the case nobody tests: set every change_p in fixtures/real-time.json to zero and reload five times. In mock mode the rows arrive in the same order every time, so five calm reloads prove little; the API makes no such promise. Now delete the tie-break from the comparator, wherever it is (an || clause, or a separate line comparing tickers), and run npm test. The tie test goes red, on every change, whoever makes it. Five reloads prove it once at best; the test proves it on every change. Put the tie-break back and restore the fixture with git restore fixtures/real-time.json.
Compare with ours
Our sortRows and the tie test
// src/lib/sort.ts
import type { Quote } from "@/lib/quotes";
import type { Row } from "@/lib/rows";
export type SortKey = "manual" | "change_p" | "volume";
const priced = (r: Row): r is Quote => !("status" in r);
export function sortRows(rows: Row[], key: SortKey, myOrder: string[]): Row[] {
if (key === "manual") {
return myOrder
.map((code) => rows.find((r) => r.code === code))
.filter((r): r is Row => Boolean(r));
}
const size = (r: Quote) => (key === "change_p" ? Math.abs(r.change_p) : r.volume ?? 0);
const byTicker = (a: Row, b: Row) => a.code.localeCompare(b.code);
return [
...rows.filter(priced).sort((a, b) => size(b) - size(a) || byTicker(a, b)),
...rows.filter((r) => !priced(r)).sort(byTicker),
];
}
// tests/sort.test.ts, the tie test
import { expect, it } from "vitest";
import type { Quote } from "@/lib/quotes";
import { sortRows } from "@/lib/sort";
const q = (code: string, change_p: number): Quote => ({
code, change_p, change: 0, close: 1, previousClose: 1, volume: 0, timestamp: 0,
});
it("orders tied rows the same way whichever way they arrive", () => {
const a = q("A", 0);
const b = q("B", 0);
const once = sortRows([a, b], "change_p", []).map((r) => r.code);
const again = sortRows([b, a], "change_p", []).map((r) => r.code);
expect(again).toEqual(once);
});
It takes the Row type from "Done means the tests are green", so a row marked unavailable has no move to sort by and goes last, by ticker. filter has already copied the array, so neither sort touches the one the page holds. Your agent's key names may differ from "change_p"; the test and the function have to use the same ones. The full state at the end of this unit is on the starter's branch ref/build-your-first-tool/u3.
Checkpoint
npm test
git status # only the files you expect, and no .env*
git add -A
git commit -m "Sort by move or volume, ties broken by ticker so the list holds still"
Read git status first: it should list the new sort function and its test, the island, the page, and any old sort function the agent removed, and no .env* file. Then answer this lesson's questions.