← All Exercises

Compute Reading Progress from Scroll Metrics

basicjavascript~15min

Background

Progress indicators must handle documents shorter than the viewport and rubber-band scrolling without showing negative values or values above 100.

Problem

Write scrollPercent(metrics) that returns how far the viewport has scrolled through a document as an integer from 0 to 100, including short pages and momentum overscroll.

Input

A JSON string with scrollTop, scrollHeight, and clientHeight.

Output

A rounded integer percentage between 0 and 100.

Sample tests

Sample 1

Input: {"scrollTop":250,"scrollHeight":1250,"clientHeight":250}
Expected: 25

Sample 2

Input: {"scrollTop":0,"scrollHeight":1250,"clientHeight":250}
Expected: 0

Sample 3

Input: {"scrollTop":1000,"scrollHeight":1250,"clientHeight":250}
Expected: 100

Sample 4

Input: {"scrollTop":1300,"scrollHeight":1250,"clientHeight":250}
Expected: 100

Sample 5

Input: {"scrollTop":0,"scrollHeight":600,"clientHeight":600}
Expected: 0

Your solution

Learning objective

Derive a safe scroll progress value from layout metrics and clamp it for edge cases.