Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Virtual list: calculate visible rows in JavaScript

108 A virtual list: which rows to render for a scroll position

fair

Ten thousand rows cannot all be in the DOM. Write windowFor, which takes the row count, a fixed row height, the viewport height, the current scrollTop and an overscan, and returns the inclusive index range to render plus the top and bottom spacer heights. Get the boundaries exactly right: a viewport that is a whole number of rows, scrolled to an exact row boundary, must render that many rows and not one more. Then do it again for rows of differing heights, using a prefix sum and a binary search.

Stuck? Three hints, smallest first
  1. 1. The first visible row is Math.floor(scrollTop / rowHeight). The last is driven by scrollTop + viewportHeight, and the subtlety is whether that lands on a boundary.
  2. 2. Assert the invariant instead of trusting the arithmetic: padTop + rendered * rowHeight + padBottom must equal the full height, for every scroll position.
  3. 3. For variable heights, build the running offsets once, then binary search for the last offset that is <= scrollTop.

The answer

const clamp = (n, low, high) => Math.min(high, Math.max(low, n));

function windowFor({ total, rowHeight, viewportHeight, scrollTop, overscan = 0 }) {
  const totalHeight = total * rowHeight;
  if (total === 0) return { first: 0, last: -1, count: 0, padTop: 0, padBottom: 0, totalHeight: 0 };

  const maxScroll = Math.max(0, totalHeight - viewportHeight);
  const top = clamp(scrollTop, 0, maxScroll);

  const firstVisible = Math.floor(top / rowHeight);
  // Subtract one pixel: a bottom edge landing exactly on a boundary belongs to
  // the row above it, not the row that starts there.
  const lastVisible = Math.floor((top + viewportHeight - 1) / rowHeight);

  const first = clamp(firstVisible - overscan, 0, total - 1);
  const last = clamp(lastVisible + overscan, 0, total - 1);
  const count = last - first + 1;

  return {
    first,
    last,
    count,
    padTop: first * rowHeight,
    padBottom: totalHeight - (last + 1) * rowHeight,
    totalHeight,
  };
}

const project = (w) => [w.first, w.last, w.count, w.padTop, w.padBottom];
const invariant = (w, rowHeight) => w.padTop + w.count * rowHeight + w.padBottom === w.totalHeight;

const atRest = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 0 });
const onABoundary = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 400 });
const onePixelPast = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 401 });
const withOverscan = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 400, overscan: 2 });
const overscanAtTheTop = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 0, overscan: 3 });
const atTheBottom = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 399600 });
const overscrolled = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: 999999 });
const shorterThanViewport = windowFor({ total: 3, rowHeight: 40, viewportHeight: 400, scrollTop: 0 });
const empty = windowFor({ total: 0, rowHeight: 40, viewportHeight: 400, scrollTop: 0 });

let invariantHolds = true;
for (let top = 0; top <= 2000; top += 7) {
  const w = windowFor({ total: 10000, rowHeight: 40, viewportHeight: 400, scrollTop: top, overscan: 2 });
  if (!invariant(w, 40)) invariantHolds = false;
}

// Variable heights: a prefix sum plus a binary search.
function variableWindow(heights, viewportHeight, scrollTop) {
  const offsets = [0];
  for (let i = 0; i < heights.length; i++) offsets.push(offsets[i] + heights[i]);
  const totalHeight = offsets[heights.length];
  const top = clamp(scrollTop, 0, Math.max(0, totalHeight - viewportHeight));

  let low = 0;
  let high = heights.length - 1;
  let first = 0;
  while (low <= high) {
    const mid = (low + high) >> 1;
    if (offsets[mid] <= top) { first = mid; low = mid + 1; } else { high = mid - 1; }
  }

  let last = first;
  while (last + 1 < heights.length && offsets[last + 1] < top + viewportHeight) last++;

  return {
    first,
    last,
    count: last - first + 1,
    padTop: offsets[first],
    padBottom: totalHeight - offsets[last + 1],
    totalHeight,
    probes: offsets.length,
  };
}

const heights = [30, 90, 30, 120, 30, 30, 200, 30];
const varTop = variableWindow(heights, 150, 0);
const varMiddle = variableWindow(heights, 150, 150);
const varBottom = variableWindow(heights, 150, 10000);
const varInvariant = [
  varMiddle.padTop + heights.slice(varMiddle.first, varMiddle.last + 1).reduce((a, b) => a + b, 0) + varMiddle.padBottom,
  varMiddle.totalHeight,
];

console.log('at rest        :', project(atRest));
console.log('on a boundary  :', project(onABoundary), 'one px past:', project(onePixelPast));
console.log('at the bottom  :', project(atTheBottom));
console.log('variable middle:', [varMiddle.first, varMiddle.last, varMiddle.padTop, varMiddle.padBottom]);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('at rest a 400px viewport of 40px rows renders exactly ten rows', project(atRest), [0, 9, 10, 0, 399600]);
test('scrolled to an exact boundary it still renders ten, not eleven', project(onABoundary), [10, 19, 10, 400, 399200]);
test('one pixel past that boundary it renders eleven, straddling two rows', project(onePixelPast), [10, 20, 11, 400, 399160]);
test('overscan widens the window on both sides and clamps at the top', [project(withOverscan), project(overscanAtTheTop)], [[8, 21, 14, 320, 399120], [0, 12, 13, 0, 399480]]);
test('at the bottom there is no bottom spacer, and overscrolling clamps to the same window', [project(atTheBottom), same(project(overscrolled), project(atTheBottom))], [[9990, 9999, 10, 399600, 0], true]);
test('a list shorter than the viewport renders all of it, and an empty one nothing', [project(shorterThanViewport), project(empty)], [[0, 2, 3, 0, 0], [0, -1, 0, 0, 0]]);
test('padTop plus rendered plus padBottom equals the full height at every position tried', invariantHolds, true);
test('with variable heights the binary search finds the row a scrollTop lands in', [[varTop.first, varTop.last], [varMiddle.first, varMiddle.last], [varBottom.first, varBottom.last]], [[0, 2], [3, 4], [6, 7]]);
test('and the spacers still account for exactly the rows not rendered', varInvariant, [560, 560]);

The - 1 in Math.floor((top + viewportHeight - 1) / rowHeight) is the entire exercise. Without it, a 400px viewport of 40px rows scrolled to exactly 400 computes a last index of 20 and renders eleven rows, one of which is a zero-pixel sliver below the fold. It is invisible, it is not a bug anyone reports, and it is a row of real DOM per scroll position for the life of the app.

The eighth assertion is the shape of test worth copying. Rather than enumerating scroll positions and their expected windows, it states the property that must hold for all of them — the spacers plus the rendered rows account for exactly the full scroll height — and checks it across a sweep. If that invariant ever breaks, the scrollbar length changes as you scroll, which is the most disorienting bug a virtual list can have.

The variable-height half is why virtual lists are hard in practice. Fixed heights make the row at a scroll position a division; differing heights make it a search, so you build the running offsets once and binary search them. What the code here does not solve is that real row heights are unknown until measured, so production implementations guess, render, measure, and patch the offsets — which shifts every offset after the corrected row and can move the content under the reader's finger.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.