diff --git a/src/array/useNumber.ts b/src/array/useNumber.ts index 6ddb6e1..e3affca 100644 --- a/src/array/useNumber.ts +++ b/src/array/useNumber.ts @@ -51,9 +51,14 @@ export function useNumber( if (upperLimit !== undefined) { if (nextValue > upperLimit) { - if (loop && lowerLimit) { - return lowerLimit; + if (loop) { + if (lowerLimit !== undefined) { + return lowerLimit; + } + + return initial; } + return upperLimit; } } @@ -61,7 +66,7 @@ export function useNumber( return nextValue; }); }, - [loop, step, upperLimit, lowerLimit], + [step, upperLimit, loop, lowerLimit, initial], ); const actions = useMemo( () => ({ diff --git a/src/index.test.ts b/src/index.test.ts index c2f682a..d5ffe6f 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -131,6 +131,39 @@ describe('useNumber', () => { expect(result.current.value).toBe(3); }); + describe('loop mode', () => { + it('should go to lowerLimit value after increase reaching upperLimit', () => { + // given + const { result } = renderHook(() => useNumber(4, { loop: true, upperLimit: 5, lowerLimit: 0 })); + const { increase } = result.current; + // when + act(() => increase()); + act(() => increase()); + // then + expect(result.current.value).toBe(0); + }); + it('should go to initial value if no lowerLimit presented after increase reaching upperLimit', () => { + // given + const { result } = renderHook(() => useNumber(4, { loop: true, upperLimit: 5 })); + const { increase } = result.current; + // when + act(() => increase()); + act(() => increase()); + // then + expect(result.current.value).toBe(4); + }); + it('should stay on upperLimit after increase reaching its value if loop equals false', () => { + // given + const { result } = renderHook(() => useNumber(4, { loop: false, upperLimit: 5 })); + const { increase } = result.current; + // when + act(() => increase()); + act(() => increase()); + // then + expect(result.current.value).toBe(5); + }); + }); + describe('hooks optimizations', () => { it('should keep actions reference equality after value change', () => { // given