Last active
February 16, 2018 05:50
-
-
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
This file contains 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
// 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