Skip to content

Conversation

@VIPAX-JIT
Copy link

@VIPAX-JIT VIPAX-JIT commented Nov 20, 2025

Resolves #8282

Changes:

This PR introduces a small but important defensive check to the map() function located in src/math/calculation.js.

Currently, when start1 === stop1, the expression:

(n - start1) / (stop1 - start1)

results in a division-by-zero case. This produces Infinity or NaN, which then propagates through subsequent drawing and color computations. These invalid values are especially confusing for beginners, as this scenario frequently occurs in sketches involving sliders, dynamic ranges, or programmatically determined bounds.

This PR adds an early return when the input range collapses, defaulting the mapped value to start2. This matches the intuitive expectation that if no mapping is possible (because the source range has zero width), the target output should fall back to its lower bound. The normal behavior of map() for all valid ranges remains fully preserved.

Why this change:

  • Prevents hard-to-debug NaN and Infinity values from appearing in sketches
  • Eliminates a common edge case encountered by beginners
  • Improves overall robustness and predictability of the math utilities
  • Fully backward-compatible and does not alter any expected API behavior
  • Aligns with p5.js’s mission of supporting learning, accessibility, and beginner-friendly design
  • Low-risk change that improves stability without touching rendering, DOM, or WebGL subsystems

Additional Notes:

This fix is intentionally minimal and avoids introducing any behavior that would alter existing valid mappings. It simply guards an undefined mathematical case while keeping the function’s logic identical for all standard uses. No documentation or unit test changes are strictly required, as the current behavior is undefined for start1 === stop1 and this PR only stabilizes that edge condition.

PR Checklist

  • npm run lint passes
  • Inline reference is included / updated
  • Unit tests are included / updated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add zero-range guard to map() to prevent NaN/Infinity when start1 equals stop1

1 participant