I’m building a carousel with a swiping limit exceeding both left and right of 45px on each item has 300px width I wonder How to convert 45 to 1 index and 345 to 2 index. I have a total of 3 items for the carousel.
I have the following formula for converting it to 2 indexes however not on the first index
If the current position is on 100px which is greater than 45 it should still result 1 index
(345 / 345 * 2) a result of 2
(45 / 345 * 2) a result of 0.2608695652173913
I’m trying to make that one line
JavaScript
x
7
1
let move = current_translate - previous_translate_item;
2
3
if (move < -345) current_index += 1;
4
if (move < -40) current_index += 1;
5
if (move > 40) current_index -= 1;
6
if (move > 345) current_index -= 1;
7
Advertisement
Answer
Try using this one:
JavaScript
1
16
16
1
let val_converter = val => -Math.sign(val)*Math.floor((Math.abs(val)-40)/300 +1);
2
3
console.log(val_converter(-645)); // 3
4
console.log(val_converter(-644)); // 2
5
console.log(val_converter(-345)); // 2
6
console.log(val_converter(-344)); // 1
7
console.log(val_converter(- 40)); // 1
8
console.log(val_converter(- 39)); // 0
9
console.log(val_converter( 0)); // 0
10
console.log(val_converter( 39)); // 0
11
console.log(val_converter( 40)); // -1
12
console.log(val_converter( 344)); // -1
13
console.log(val_converter( 345)); // -2
14
console.log(val_converter( 644)); // -2
15
console.log(val_converter( 645)); // -3
16
In your specific source code, it would be something like this:
JavaScript
1
6
1
let val_converter = val => -Math.sign(val)*Math.floor((Math.abs(val)-40)/300+1);
2
3
let move = current_translate - previous_translate_item;
4
5
current_index += val_converter(move);
6