function safeIndex(index, size, dimension = null, boundsCheck = true) {
    if (index < -size || index >= size) {
        if (boundsCheck) {
            throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);
        } else {
            return index < -size ? 0 : size;
        }
    }

    if (index < 0) {
        // Negative indexing, ensuring positive index
        index = ((index % size) + size) % size;
    }
    return index;
}
Safely calculate the index for an array of a given size, allowing negative indexing.
@param {number} index The index that will be used.
@param {number} size The size of the array.
@param {number} [dimension=null] The dimension that the index is for (optional).
@returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.

@throws {Error} If the index is out of range.
@private