I have two values that indicate how many results to parse from some data and which nth item I want to target. In this case, it's making every nth item a large image where as the rest are normal size. Here's what I need the loop to do:
- First image must be large, or have the option to turn on
- Get the remainder of normal size images at the end
- Use this remainder so that the next iteration over the data has the correct starting point before the next large image appears.
I got very close but my modulus is wrong or how i'm doing the checking.
var i = 0,
len = productsObj.products.length;
for (i; i < len; i++) {
if ((i + this.nthProductImageOffset) % NTH_PRODUCT_IS_LARGE_TILE === 0) {
productsObj.products[i].PhotoSize = 'large';
} else {
productsObj.products[i].PhotoSize = 'medium';
}
}
// Store the remainder of medium tiles, if any, to be calculated
// against the next set of products to be appended.
this.nthProductImageOffset = i % NTH_PRODUCT_IS_LARGE_TILE;
So, if my two initial values were: NTH_PRODUCT_IS_LARGE_TILE = 7 productsObj.products.length = 30
First image is large, then every 7th image is large. If we are left with a remainder of 2 medium images at the end of the loop, that needs to be accounted for the next time we run the loop before another large image appears. This way, regardless of the nth number or the number of iterations, we will always have the correct number of medium tiles in between the large ones.