UNPKG

@mirawision/reactive-hooks

Version:

A comprehensive collection of 50+ React hooks for state management, UI interactions, device APIs, async operations, drag & drop, audio/speech, and more. Full TypeScript support with SSR safety.

79 lines (78 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useIterator = useIterator; const react_1 = require("react"); /** * A hook that provides iteration over an array or numeric range. * When given a number n, iterates over range [0..n-1]. * * @param items Array of items or number for range * @param opts Options for iteration behavior * @returns Object containing current state and control functions * * @example * // Array iteration * const { value, next, hasNext } = useIterator(['a', 'b', 'c']); * * @example * // Range iteration with loop * const { value, next } = useIterator(3, { loop: true }); */ function useIterator(items, opts = {}) { const { loop = false } = opts; // Convert number to range array indices const range = (0, react_1.useMemo)(() => { if (typeof items === 'number') { return { length: Math.max(0, items), isRange: true }; } return { length: items.length, isRange: false }; }, [items]); const [index, setIndex] = (0, react_1.useState)(0); // Get current value const value = (0, react_1.useMemo)(() => { if (range.length === 0) return range.isRange ? 0 : undefined; if (range.isRange) return index; return items[index]; }, [items, index, range]); // Check if movement is possible const hasNext = (0, react_1.useMemo)(() => { return loop || index < range.length - 1; }, [loop, index, range.length]); const hasPrev = (0, react_1.useMemo)(() => { return loop || index > 0; }, [loop, index]); // Move to next item const next = (0, react_1.useCallback)(() => { setIndex(current => { if (current >= range.length - 1) { return loop ? 0 : current; } return current + 1; }); }, [loop, range.length]); // Move to previous item const prev = (0, react_1.useCallback)(() => { setIndex(current => { if (current <= 0) { return loop ? range.length - 1 : current; } return current - 1; }); }, [loop, range.length]); // Set specific index const set = (0, react_1.useCallback)((newIndex) => { const validIndex = Math.max(0, Math.min(newIndex, range.length - 1)); setIndex(validIndex); }, [range.length]); return { index, value: value, next, prev, set, hasNext, hasPrev, }; }