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
let move = current_translate - previous_translate_item; if (move < -345) current_index += 1; if (move < -40) current_index += 1; if (move > 40) current_index -= 1; if (move > 345) current_index -= 1;
Advertisement
Answer
Try using this one:
let val_converter = val => -Math.sign(val)*Math.floor((Math.abs(val)-40)/300 +1); console.log(val_converter(-645)); // 3 console.log(val_converter(-644)); // 2 console.log(val_converter(-345)); // 2 console.log(val_converter(-344)); // 1 console.log(val_converter(- 40)); // 1 console.log(val_converter(- 39)); // 0 console.log(val_converter( 0)); // 0 console.log(val_converter( 39)); // 0 console.log(val_converter( 40)); // -1 console.log(val_converter( 344)); // -1 console.log(val_converter( 345)); // -2 console.log(val_converter( 644)); // -2 console.log(val_converter( 645)); // -3
In your specific source code, it would be something like this:
let val_converter = val => -Math.sign(val)*Math.floor((Math.abs(val)-40)/300+1); let move = current_translate - previous_translate_item; current_index += val_converter(move);