Skip to content

Instantly share code, notes, and snippets.

@mendes5
Created December 21, 2020 13:15
Show Gist options
  • Select an option

  • Save mendes5/67be143ee3c9729720d686915e425b80 to your computer and use it in GitHub Desktop.

Select an option

Save mendes5/67be143ee3c9729720d686915e425b80 to your computer and use it in GitHub Desktop.
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