diff --git a/src/arrayf/arrayf.ts b/src/arrayf/arrayf.ts index c53ee4696a..5e99278cd0 100644 --- a/src/arrayf/arrayf.ts +++ b/src/arrayf/arrayf.ts @@ -28,5 +28,23 @@ export class arrayf { return output; } - -} \ No newline at end of file + /** + * Given an index that could be out-of-range for an array of the given + * length, it will return a valid index, as if the array values looped + * infinitely. + * + * ``` + * wrapIndex(2, 7); // Returns 2 + * wrapIndex(10, 7); // Returns 3 + * wrapIndex(21, 7); // Returns 0 + * wrapIndex(-1, 7); // Returns 6 + * ``` + */ + static wrapIndex(index: number, length: number): number { + if (index < 0) { + return length + (index % length); + } else { + return index % length; + } + } +}