Extract shared list and numeric input helpers

This commit is contained in:
Jage9
2026-02-22 16:41:19 -05:00
parent 481a7550cf
commit 2bcd165d3b
4 changed files with 60 additions and 69 deletions

View File

@@ -0,0 +1,27 @@
export function cycleIndex(currentIndex: number, length: number, direction: 'next' | 'prev'): number {
if (length <= 0) return 0;
if (direction === 'next') {
return (currentIndex + 1) % length;
}
return (currentIndex - 1 + length) % length;
}
export function findNextIndexByInitial<T>(
entries: readonly T[],
currentIndex: number,
key: string,
labelFor: (entry: T) => string,
): number {
if (entries.length === 0 || key.length !== 1 || !/[a-z]/i.test(key)) {
return -1;
}
const target = key.toLowerCase();
for (let step = 1; step <= entries.length; step += 1) {
const candidateIndex = (currentIndex + step) % entries.length;
const label = labelFor(entries[candidateIndex]).trim().toLowerCase();
if (label.startsWith(target)) {
return candidateIndex;
}
}
return -1;
}

View File

@@ -0,0 +1,19 @@
export function snapNumberToStep(value: number, step: number, anchor = 0): number {
if (!(step > 0) || !Number.isFinite(value) || !Number.isFinite(anchor)) {
return value;
}
const normalized = Math.round((value - anchor) / step) * step + anchor;
const decimals = step >= 1 ? 0 : Math.min(6, Math.ceil(Math.abs(Math.log10(step))) + 1);
return Number(normalized.toFixed(decimals));
}
export function formatSteppedNumber(value: number, step: number): string {
const decimals = step >= 1 ? 0 : Math.min(6, Math.ceil(Math.abs(Math.log10(step))) + 1);
if (decimals <= 0) {
return String(Math.round(value));
}
return value
.toFixed(decimals)
.replace(/(\.\d*?[1-9])0+$/u, '$1')
.replace(/\.0+$/u, '');
}