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);