Skip to content

LoopIndex fails when given an index that is less than -List.Count. #1

Description

@pflannery

You probably know this already but I just wanted to point out that the LoopIndex method fails when given an index that is less than -List.Count.

For example this fails:

// fails
int count = 360;
int index = -361;
int invalidIndex = (index + count) % count;
Console.WriteLine(invalidIndex); // writes -1

Here is a solution that preserves the original function output but also supports indexes less than -List.Count

// solution
int count = 360;
int index = -361;
int i = index % count;
if ((i < 0 && count > 0) || (i > 0 && count < 0)) i = i + count;
Console.WriteLine(i); // writes 359

The solution only performs i+count when the signs of i and count are different.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions