← All Exercises
Focus Trap Tab Cycle Index
intermediatejavascript
Background
Modal dialogs and drawers keep keyboard focus inside a container. The trap must skip disabled controls and wrap in both directions, otherwise keyboard users can get stuck or escape the dialog.
Problem
Implement nextFocusableIndex(count, disabled, current, shift). Simulate a focus trap: moving forward finds the next index that is not disabled and wraps from the last index to the first; moving backward wraps from the first index to the last. Return -1 when no element can receive focus.
Input
A JSON object with count, disabled (array of indexes), current, and shift (true for backward movement).
Output
The next focusable index, or -1 when every element is disabled or the list is empty.
Sample tests
Sample 1
Input: {"count":5,"disabled":[2],"current":1,"shift":false}Expected: 3
Sample 2
Input: {"count":5,"disabled":[2],"current":0,"shift":true}Expected: 4
Sample 3
Input: {"count":4,"disabled":[0,1,2,3],"current":0,"shift":false}Expected: -1
Sample 4
Input: {"count":5,"disabled":[4],"current":3,"shift":false}Expected: 0
Sample 5
Input: {"count":5,"disabled":[2],"current":2,"shift":false}Expected: 3
Your solution
Learning objective
Implement keyboard focus cycling for modal dialogs and understand directional modulo wrapping and disabled-state filtering.