← All Exercises

Virtual List Window Calculator

advancedjavascript~15min

Background

Virtual scrolling keeps large lists fast by rendering only the rows near the viewport. The window math must include partially visible rows and overscan rows, or users see blank gaps while scrolling.

Problem

Given scrollTop, viewportHeight, itemHeight, itemCount, and overscan, compute the first and last rendered indexes plus the offset of the first rendered row. Account for a partially scrolled row at the top and clamp both ends to the list bounds.

Input

A JSON object with scrollTop, viewportHeight, itemHeight, itemCount, and overscan.

Output

A JSON object with start, end, offset, and count, where offset is start multiplied by itemHeight.

Sample tests

Sample 1

Input: {"scrollTop":420,"viewportHeight":300,"itemHeight":40,"itemCount":100,"overscan":2}
Expected: {"start":8,"end":19,"offset":320,"count":12}

Sample 2

Input: {"scrollTop":0,"viewportHeight":300,"itemHeight":40,"itemCount":100,"overscan":2}
Expected: {"start":0,"end":9,"offset":0,"count":10}

Sample 3

Input: {"scrollTop":3700,"viewportHeight":300,"itemHeight":40,"itemCount":100,"overscan":2}
Expected: {"start":90,"end":99,"offset":3600,"count":10}

Sample 4

Input: {"scrollTop":0,"viewportHeight":300,"itemHeight":40,"itemCount":0,"overscan":2}
Expected: {"start":0,"end":-1,"offset":0,"count":0}

Your solution

Learning objective

Practice windowed rendering math, off-by-one reasoning at scroll boundaries, and clamping for virtualized lists.