UNPKG

etc-hooks

Version:
44 lines (43 loc) 1.26 kB
import { __assign, __read } from "tslib"; import { useState } from "react"; import { clamp } from "../utils"; var DEFAULT_OPTIONS = { min: -Infinity, max: Infinity }; var useCounter = function useCounter(initialValue, options) { if (initialValue === void 0) { initialValue = 0; } if (options === void 0) { options = DEFAULT_OPTIONS; } var _a = __assign(__assign({}, DEFAULT_OPTIONS), options), min = _a.min, max = _a.max; var _b = __read(useState(clamp(initialValue, min, max)), 2), count = _b[0], setCount = _b[1]; var set = function set(value) { return setCount(clamp(value, min, max)); }; var reset = function reset() { return setCount(clamp(initialValue, min, max)); }; var increment = function increment() { return setCount(function(current) { return clamp(current + 1, min, max); }); }; var decrement = function decrement() { return setCount(function(current) { return clamp(current - 1, min, max); }); }; return [ count, { set: set, reset: reset, increment: increment, decrement: decrement } ]; }; export default useCounter;