优雅的算法来控制轮播的最大值
我有一个滑块最多可以显示 3 个元素。如果有更多元素,这些元素将被隐藏并
可以通过单击左右进入视图,如下图所示。
这个滑块将接受一个位置支柱。请注意,我无法更改此外部组件。
<Slider position={position} />
位置值决定红色位置,如下图所示。
我正在尝试使用一种算法来按照以下规则设置此位置。
如果元素为 3 或更少,则位置应始终为 0。
除此之外,它不应滑过最后一个元素。
这意味着,假设我传入值 4(即索引 4,第 5 个元素)作为位置值,该组件将如下所示。
以上是错误的。它应该如下所示,其中填充了 3 个位置,同时仍然尽可能向左滑动。
因此,如果我将位置值传递为 2,效果会很好。
也可以按原样使用位置值(如果可以接受),无需按如下方式进行修改。
寻找算法:
获取位置值,并根据元素计数和最大可见元素(3)决定是否可以按原样使用或需要修改。 并获取修改后的位置值并将其传递给Slider组件。
正在思考以下内容。
根据测试,相信这项工作。正在寻找验证这是否有效。
如果有办法让我变得更优雅并且可能没有的话,请提供建议
初始 if 检查是否小于或等于 3 个元素。
// 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;
}
注意:这本质上是一个 React 项目,但考虑到查询与算法更多相关,因此没有对其进行标记。谢谢。
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.
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.
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.
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.
Also to use position value as is if acceptable without needing to modify it as follows.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论