24/28
Part 6 of 6 · Follow-upsLearn and do

What if rows load as the viewer scrolls down?

A real homepage doesn't build all its rows at once. It renders the first few, and builds more as the viewer scrolls down. Then dedup_homepage(rows, width) has nothing to loop over. Each row arrives alone, and the page has to remember what it shows between calls.

That memory is state, so it belongs in an object: a Homepage that makes its own shown set, and places each row with place_row as the row arrives.

One Homepage per viewer's page load. Each call to add places one row against everything above it, in the order the rows arrive.

The trap is where the set is made:

class Homepage:
    # one set, shared by every Homepage
    shown = set()

A set written in the class body is made once, when the class is defined, and every instance shares it. The first viewer's titles then block the second viewer's screen. A test with one page passes. Two pages catch it.

Two more questions an interviewer may add here, with short answers:

  • Rows below the first screen. Under level 1 every row's head counts. On a real page, rows below the first screen could reset or use their own rule. Ask which.
  • Many servers. The set is per page load, so it never leaves one request. Nothing needs to be shared.

In the editor, place_row is given. Write the class Homepage with __init__ and add(row, width).