Skip to content

Instantly share code, notes, and snippets.

@Maximilianos
Created May 30, 2016 18:39
Show Gist options
  • Save Maximilianos/bc194e4a55c5050fcbe2567f084bfa17 to your computer and use it in GitHub Desktop.
Save Maximilianos/bc194e4a55c5050fcbe2567f084bfa17 to your computer and use it in GitHub Desktop.
fit the given number within the available indexes of an array of a given length and overflow around from the end or beginning where appropriate
/**
* Fit a given index into a given array
* length, while properly handling overflow
*
* so for eg:
* - given length=10 & index=3 -> return 3
* - given length=10 & index=14 -> return 4 (overflow)
* - given length=10 & index=-2 -> return 8 (overflow)
*
* @param index
* @param length
* @returns {number}
*/
export default function fitIndex(index, length) {
return ((index % length) + length) % length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment