Elegant algorithm to control max value for carousel

I have a slider which at most can show 3 elements. If there are more elements, these are hidden and

can come into view by clicking left right as following image.

enter image description here

This slider will be taking in a position prop. Note that I can’t change this component which is external.

<Slider position={position} />

The position value decide the red position as shown in following image.

enter image description here

I am trying to have an algorithm to set this position with following rules.

If the elements are 3 or less, position should always be 0.

Anything more, it should not slide past the last element.

Meaning let’s say I pass in the value 4 (so index 4, 5th element) for the position value, the component will look like the following.

enter image description here

Above is wrong. It should look like the following where it filled 3 spots while still sliding to the left as much as possible.

Thus it would have worked fine if I passed in the position value as 2.

enter image description here

Also to use position value as is if acceptable without needing to modify it as follows.

enter image description here

Looking for algorithm that will:

Get a position value and decide if it can be used as is or need to amend based on element count and the max visible elements which is 3.
And obtain a modified position value and pass it to the Slider component.

Was thinking something along the line of the following.

Based on testing, believe this work. Looking for validation if this would work.

And advice if there is a way I could make this more elegant and possibly not have

the initial if check for the less than or equals 3 elements.

// elementCount = // dynamic count of elements.
// initialPosition = // initial position being passed in which needs to be validated.
const getPosition = (elementCount, initialPosition) => {
    if (elementCount <= 3) {
        return 0;
    }
    const maxPosition = elementCount - 3;
    return initialPosition <= maxPosition ? initialPosition : maxPosition;
}

Note: This is essentially a React project but didn’t tag it as so considering the query is more algorithm related. Thanks.