From 60310e251aebed1179eab01bf649d7f14c76ed3c Mon Sep 17 00:00:00 2001 From: Sulthon Zainul Habib <4921059+sulthonzh@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:06:49 +0700 Subject: [PATCH] fix(hanoi-tower): stop infinite recursion for zero or negative number 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. --- .../hanoi-tower/__test__/hanoiTower.test.js | 23 +++++++++++++++++++ .../uncategorized/hanoi-tower/hanoiTower.js | 7 ++++++ 2 files changed, 30 insertions(+) diff --git a/src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js b/src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js index d720d1839f..e9a32871b5 100644 --- a/src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js +++ b/src/algorithms/uncategorized/hanoi-tower/__test__/hanoiTower.test.js @@ -59,4 +59,27 @@ describe('hanoiTower', () => { expect(moveCallback).toHaveBeenCalledTimes((2 ** numberOfDiscs) - 1); }); + it('should solve tower of hanoi puzzle with 0 discs', () => { + const moveCallback = jest.fn(); + + hanoiTower({ + numberOfDiscs: 0, + moveCallback, + }); + + expect(moveCallback).not.toHaveBeenCalled(); + }); + + it('should solve tower of hanoi puzzle with negative number of discs', () => { + const moveCallback = jest.fn(); + + expect(() => { + hanoiTower({ + numberOfDiscs: -3, + moveCallback, + }); + }).not.toThrow(); + + expect(moveCallback).not.toHaveBeenCalled(); + }); }); diff --git a/src/algorithms/uncategorized/hanoi-tower/hanoiTower.js b/src/algorithms/uncategorized/hanoi-tower/hanoiTower.js index 86d78880d2..97c7a9b3e4 100644 --- a/src/algorithms/uncategorized/hanoi-tower/hanoiTower.js +++ b/src/algorithms/uncategorized/hanoi-tower/hanoiTower.js @@ -69,6 +69,13 @@ export default function hanoiTower({ // that might contain elements (discs). Each disc is represented as a number. // Larger discs have bigger number equivalent. + // If there are no discs to move then the puzzle is already solved. + // This also guards the recursion from infinitely calling itself + // in case if numberOfDiscs is zero or negative. + if (numberOfDiscs <= 0) { + return; + } + // Let's create the discs and put them to the fromPole. for (let discSize = numberOfDiscs; discSize > 0; discSize -= 1) { fromPole.push(discSize);