summaryrefslogtreecommitdiff
path: root/shared/components/src/utils/getUpdatedFocusedIndex.ts
blob: ca2c765eb9f856c0d7ce553ea16eec01e99b8d9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
export function getUpdatedFocusedIndex(
    incrementAmount: number,
    currentFocusedIndex: number | null,
    numberOfItems: number,
): number {
    const potentialFocusedIndex = incrementAmount + currentFocusedIndex;

    if (incrementAmount > 0) {
        if (currentFocusedIndex === null) {
            return 0;
        } else {
            return potentialFocusedIndex >= numberOfItems
                ? 0
                : potentialFocusedIndex;
        }
    } else {
        if (currentFocusedIndex === null) {
            return numberOfItems - 1;
        } else {
            return potentialFocusedIndex < 0
                ? numberOfItems - 1
                : potentialFocusedIndex;
        }
    }
}