← All Exercises

Intersection Visible Ratio Calculator

intermediatejavascript~15min

Background

Lazy images, ad viewability, and animation triggers depend on how much of an element is on screen. The ratio is the intersection area over the target area, not over the viewport area.

Problem

Implement visibleRatio(root, target) for axis-aligned rectangles with left, right, top, and bottom coordinates. Return the intersection area divided by the target area, rounded to four decimal places. A zero-area target has a ratio of 0, and rectangles that do not overlap return 0.

Input

A JSON object with root and target rectangles, each having left, right, top, and bottom as numbers.

Output

A plain decimal string between 0 and 1, such as 0.5 or 1.

Sample tests

Sample 1

Input: {"root":{"left":0,"right":1000,"top":0,"bottom":600},"target":{"left":0,"right":1000,"top":550,"bottom":650}}
Expected: 0.5

Sample 2

Input: {"root":{"left":0,"right":1000,"top":0,"bottom":600},"target":{"left":100,"right":300,"top":100,"bottom":200}}
Expected: 1

Sample 3

Input: {"root":{"left":0,"right":1000,"top":0,"bottom":600},"target":{"left":0,"right":1000,"top":700,"bottom":800}}
Expected: 0

Sample 4

Input: {"root":{"left":0,"right":100,"top":0,"bottom":20},"target":{"left":50,"right":150,"top":0,"bottom":20}}
Expected: 0.5

Sample 5

Input: {"root":{"left":0,"right":100,"top":0,"bottom":20},"target":{"left":10,"right":10,"top":0,"bottom":20}}
Expected: 0

Your solution

Learning objective

Practice rectangle intersection math and understand the ratio semantics behind visibility APIs.