Skip to content

fix(hanoi-tower): stop infinite recursion for zero or negative number of discs - #2255

Open
sulthonzh wants to merge 1 commit into
trekhleb:masterfrom
sulthonzh:fix/hanoi-tower-zero-discs
Open

sulthonzh wants to merge 1 commit into
trekhleb:masterfrom
sulthonzh:fix/hanoi-tower-zero-discs

Conversation

@sulthonzh

Copy link
Copy Markdown

Problem

hanoiTower({ numberOfDiscs: 0 }) (or any negative count) never reaches the numberOfDiscs === 1 base case and recurses until RangeError: Maximum call stack size exceeded. With no discs to move, the puzzle is trivially already solved, so the function should simply do nothing (zero moves).

Fix

Guard the public entry point of hanoiTower with an early return for numberOfDiscs <= 0. The recursion itself always calls with counts >= 1, so guarding the entry is sufficient. Algorithm behavior for numberOfDiscs >= 1 is untouched.

Tests

Adds two regression tests to the existing suite (0 discs → no moves, no throw; -3 discs → same).

Verified before submitting (per CONTRIBUTING):

  • npm test — 589/589 pass (full suite)
  • npm run lint — clean on touched files
  • Coverage of hanoiTower.js — 100% statements / branches / functions / lines

… of discs

Calling hanoiTower({ numberOfDiscs: 0 }) (or a negative count) never
reached the numberOfDiscs === 1 base case and recursed until
"RangeError: Maximum call stack size exceeded". Guard the entry point:
with no discs to move the puzzle is already solved. Adds regression
tests for 0 and negative disc counts.
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.

1 participant