Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active February 16, 2018 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/2642d0b6140d615149402dfdcfd92602 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/2642d0b6140d615149402dfdcfd92602 to your computer and use it in GitHub Desktop.
Bound a positive and negative position index by a range of indices - Useful for indexing in-between elements in an array #js
// imagine you have an array like [E1,E2]
// normally an index into this array is just:
// 0 -> E1 (firstIndex)
// 1 -> E2 (lastIndex)
// now you want to be able to refer to positions in between the elements in positive and negative manner
// (this can be used for both insertion and also retrieval!)
// [ E1 E2 ]
// ^ ^ ^
// | | |
// 0 1 2
// -3 -2 -1
// but you also need to bound positions which are out of range
// numbers that is greater than the last index or less than the first index
// so positive out-of-range transforms like: -4, -5... => -3
// or negative out-of-range transforms like: 3, 4... => 2
// then this function does this!
function boundIndex (
position,
length,
shift = true
) {
if (length === 0) return 0;
const lastIndex = length - 1;
if (position < 0) {
const lastIndexNegative = -(lastIndex + 2);
if (position < lastIndexNegative) {
position = lastIndexNegative;
}
} else if (position > lastIndex) {
position = lastIndex + 1;
}
// position is now a bounded negative or positive number
// we can shift it to the positive range if necessary
if (shift && position < 0) {
position += lastIndex + 2;
}
return position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment