AniUI Academy
medium+250 XPPractice

Compute a virtual list's visible range

Rendering ten thousand rows kills a page, so virtualised lists render only the rows in view plus a small buffer, and offset them so the scrollbar still behaves. All of that is one small pure calculation, and it is worth getting exactly right — off by one here and rows flicker at the edges.

Implement visibleRange({ scrollTop, rowHeight, viewportHeight, totalRows, overscan = 0 }) returning { start, end, offsetTop }, where start and end are row indices and end is **inclusive**.

Treat a negative scrollTop as 0, since overscroll bounce can produce one. Then start is Math.floor(scrollTop / rowHeight) - overscan, clamped to at least 0 and at most totalRows - 1. And end is Math.ceil((scrollTop + viewportHeight) / rowHeight) - 1 + overscan, clamped to at most totalRows - 1 and never less than start. offsetTop is start * rowHeight — the padding or translateY that puts the first rendered row in the right place.

When totalRows is 0 there is nothing to render, so return exactly { start: 0, end: -1, offsetTop: 0 }.

What it has to do

  • Return { start, end, offsetTop } with an inclusive end.
  • Subtract overscan from the start and add it to the end, defaulting overscan to 0.
  • Clamp both indices into 0 .. totalRows - 1 and never let end fall below start.
  • Compute offsetTop as start * rowHeight.
  • Return { start: 0, end: -1, offsetTop: 0 } when totalRows is 0.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.