I'm trying to figure this out elegantly, but I think I've just gotten myself confused. With an array input of arbitrary length and contents (e.g., [0,1,2,3,4,5,...]
) I'd like the output to be:
[
{ slide: 0, style: 'A' },
{ slide: 1, style: 'A' },
{ slide: 2, style: 'B' },
{ slide: 3, style: 'B' },
{ slide: 4, style: 'A' },
{ slide: 5, style: 'A' },
{ slide: 6, style: 'B' },
{ slide: 7, style: 'B' },
{ slide: 8, style: 'A' },
{ slide: 9, style: 'A' },
{ slide: 10, style: 'B' },
{ slide: 11, style: 'B' },
...
]
So just the A A B B
pattern repeated.
This is what I've tried, but it seems to break down after a few iterations.
const slides = [...Array(24).keys()];
const getStyleForIndex = (index) => {
if ((index) % 4 === 0 || (index) % 5 === 0 || index === 1) {
return 'A';
}
return 'B';
};
const newSlides = slides.map((slide, index) => ({ slide: slide, style: getStyleForIndex(index) }));
console.log(newSlides);
Any help wrangling the modulus operator here would be much appreciated!
You should be using index % 4
in both cases, not index % 5
. This returns a sequence of numbers that cycle through 0, 1, 2, 3
.
if (index % 4 == 0 || index % 4 == 1) {
return 'A';
} else {
return 'B';
}
or more simply:
return index % 4 < 2 ? 'A' : 'B';