Last active
March 3, 2025 20:38
-
-
Save pierodev0/a392864b818138864913728bfada351b to your computer and use it in GitHub Desktop.
opcional min max
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
type UseCounterConfig = { | |
min?: number; | |
max?: number; | |
}; | |
type CounterActions = { | |
increment: () => void; | |
decrement: () => void; | |
set: (value: number) => void; | |
reset: () => void; | |
}; | |
export function useCounter( | |
initialValue: number, | |
config: UseCounterConfig = {}, | |
): [number, CounterActions] { | |
const [count, setCount] = useState(initialValue); | |
const { min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER } = config; | |
const increment = () => { | |
setCount((prevCount) => (prevCount + 1 > max ? max : prevCount + 1)); | |
}; | |
const decrement = () => { | |
setCount((prevCount) => (prevCount - 1 < min ? min : prevCount - 1)); | |
}; | |
const set = (value: number) => setCount(value); | |
const reset = () => setCount(initialValue); | |
return [ | |
count, | |
{ | |
increment, | |
decrement, | |
set, | |
reset, | |
}, | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment