Files
sui/src/lib/numeric-utils.ts
2025-12-11 15:20:42 -08:00

68 lines
1.6 KiB
TypeScript

/**
* numeric-utils.ts
* Utility functions for numeric input manipulation.
*/
/**
* incrementValue increments the value of the input by 1
* @param input The input element to increment
* @param max The maximum value of the input
* @param start The starting value of the input
* @returns true if the value was incremented, false if it looped back to 0
*/
export const incrementValue = (
input: HTMLInputElement,
opts: { max?: number; start: number }
): boolean => {
if (input.value.length === 0) {
input.value = opts.start.toString();
return true;
}
const value = parseInt(input.value);
if (value === opts.max) {
input.value = opts.start.toString();
return false;
} else if (opts.max && value > opts.max) {
input.value = (value - opts.max).toString();
return false;
} else {
input.value = (value + 1).toString();
return true;
}
};
/**
* decrementValue decrements the value of the input by 1
* @param input The input element to decrement
* @param max The maximum value of the input
* @param start The starting value of the input
* @returns true if the value was decremented, false if it looped back to max
*/
export const decrementValue = (
input: HTMLInputElement,
opts: { max?: number; start: number }
): boolean => {
const setToMax = (): boolean => {
if (opts.max) {
input.value = opts.max.toString();
return true;
} else {
input.value = '0';
return false;
}
};
if (input.value.length === 0) {
return setToMax();
}
const value = parseInt(input.value);
if (value <= opts.start) {
return !setToMax();
} else {
input.value = (value - 1).toString();
return true;
}
};