Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Wrap an Index

Fundamentals: Part 1medium

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 13: Basic Operators

Implement `wrapIndex(i, len)` returning `i` wrapped into the range `0..len-1`, handling negative indices.

Sample tests

Input: wrapIndex(7, 5)
Output: 2
Input: wrapIndex(-1, 5)
Output: 4

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • i % len alone returns a negative remainder for negative indices in JavaScript.

Learning resources

  • MDN: Expressions and operators
Approach & explanation (try first)

Adding len and taking the modulus again folds negative results back into the 0..len-1 range.

Loading...
⌘/Ctrl + Enter

Run your code to see results.