Created
May 20, 2014 01:39
-
-
Save mariodivece/438d4fac56ed7149a96b to your computer and use it in GitHub Desktop.
Extension methods that perform circular-addressing math on 0-index based arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Unosquare.Utilities | |
{ | |
public static class Extensions | |
{ | |
static public int CircleOffset(this int currentIndex, int offset, int lastIndex) | |
{ | |
var newIndex = currentIndex + offset; | |
return newIndex.CircleIndex(lastIndex); | |
} | |
static public int CircleIndex(this int currentIndex, int lastIndex) | |
{ | |
var newIndex = currentIndex; | |
if (currentIndex > lastIndex) | |
{ | |
newIndex = currentIndex % (lastIndex + 1); | |
} | |
else if (currentIndex < 0) | |
{ | |
newIndex = lastIndex + currentIndex + 1; | |
newIndex = newIndex.CircleIndex(lastIndex); | |
} | |
return newIndex; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment