Created
December 21, 2020 13:15
-
-
Save mendes5/67be143ee3c9729720d686915e425b80 to your computer and use it in GitHub Desktop.
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
| const cycleValue = (value: number, cycleLength: number): number => { | |
| if (value > 0) return value % cycleLength; | |
| if (value < 0) return value + cycleLength; | |
| return 0; | |
| }; | |
| /** | |
| * Given a cycleLength, this hook will return a value that is | |
| * in the range of 0 and cycleLength. It also return methods to change | |
| * the value while ensuring that they never get out of bounds or negative. | |
| */ | |
| export const useCycliceRange = (cycleLength: number): UseRangeHelpers => { | |
| const [value, setValue] = React.useState(0); | |
| const setTo = React.useCallback( | |
| (value: number) => { | |
| setValue(cycleValue(value, cycleLength)); | |
| }, | |
| [cycleLength] | |
| ); | |
| const goBackward = React.useCallback(() => { | |
| setValue((value) => cycleValue(value - 1, cycleLength)); | |
| }, [cycleLength]); | |
| const goForward = React.useCallback(() => { | |
| setValue((value) => cycleValue(value + 1, cycleLength)); | |
| }, [cycleLength]); | |
| return [ | |
| value, | |
| { | |
| goBackward, | |
| goForward, | |
| setTo, | |
| }, | |
| ]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment