From a9f85b9ebf1331561554bdc41e2d6fb1b375f4bc Mon Sep 17 00:00:00 2001 From: Angus MacDonald Date: Fri, 27 Nov 2020 12:29:49 -0600 Subject: [PATCH] Add arrayf.wrapIndex --- src/arrayf/arrayf.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) 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; + } + } +}