Created
June 29, 2021 19:41
-
-
Save clucasalcantara/727fc4904c1ce346b37b437019ec5103 to your computer and use it in GitHub Desktop.
Carousel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculates what position the carousel | |
* should be after receive a instructions set | |
*/ | |
const evaluateCarouselPosition = ( | |
instructions = ">>><>", | |
currentPosition = 0, | |
length = 7 | |
) => { | |
// Vamo lá, vou fazer com reduce first | |
// O Split por espaço ('') é pra pegar cada instrução | |
// separadamente | |
const carouselIndex = instructions | |
.split("") | |
// Aqui entramos no reduce, o primeiro parametro do reduce sempre é o acumulador | |
// ou seja, o lugar onde a gente vai apresentar a logica do resultado final | |
// O segundo é o item do array (um de cada vez) | |
.reduce((finalPosition, instruction) => { | |
console.log("Actual carousel position", { carouselIndex: finalPosition }) | |
console.log("Instruction", { instruction }) | |
if (instruction === ">") { | |
// Aqui nesse bloco, a gente pega se a posição atual do usuário | |
// é o final do array, se for e ele avançar, voltamos a posição dele pro começo | |
if (currentPosition === length - 1) { | |
return (finalPosition = 0) | |
} | |
// Não é o final do array, avançamos normal | |
return (finalPosition += 1) | |
} | |
// Aqui nesse bloco, a gente pega se a posição atual do usuário | |
// é o começo do array, se for, e ele voltar, voltamos a posição dele pro final | |
if (instruction === "<") { | |
if (finalPosition === 0) { | |
return (finalPosition = length - 1) | |
} | |
// Não é o começo do array, voltamos normal | |
return (finalPosition -= 1) | |
} | |
console.log("Updated position", { carouselIndex: finalPosition }) | |
}, currentPosition) | |
console.log("After these instructions the carousel index is:", { | |
carouselIndex, | |
}) | |
} | |
evaluateCarouselPosition() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment