Optimized rows in javascript

Date: 2016-07-04
var getOptimizedRowSize = function (minItemsPerRow, maxItemsPerRow, itemCount) {
	var highestRest = 0;
	var highestRestItemsPerRow = 0;

	if (itemCount < maxItemsPerRow) {
		return Math.max(minItemsPerRow, itemCount);
	}

	for (var i = maxItemsPerRow; i >= minItemsPerRow; i = (i - 1) | 0) {
		var rest = itemCount % i;
		if (rest === 0) {
			return i;
		}
		else  {
			if (rest > highestRest) {
				highestRest = rest;
				highestRestItemsPerRow = i;

				if (highestRest >= ((maxItemsPerRow - 1) | 0) && itemCount > maxItemsPerRow) {
					return i;
				}
			}
		}
	}

	if (highestRestItemsPerRow === 0) {
		highestRestItemsPerRow = maxItemsPerRow;
	}

	return highestRestItemsPerRow;
}

var getResultForArray = function(array) {
	var count = array.length;
	var maxItemsInOneRow = getOptimizedRowSize(3, 5, count);
	var index = 0;
	var row = 0;

	var result = { count: count, itemsPerRow: maxItemsInOneRow, rows: []};
	//console.log('total items', count);
	//console.log('maxItemsInOneRow', maxItemsInOneRow);
	while(index < count) {
		var itemsLeft = count - index;
		var itemsInRow = Math.min(itemsLeft, maxItemsInOneRow);
		//console.log('row', row, 'item count', itemsInRow);
		result.rows.push({ [row]: itemsInRow  });
		index += itemsInRow;
		row += 1;
	}
	console.log(JSON.stringify(result));
}

var array = [];
for(var i=1;i<30;i+=1) {
	array.push(i);
	getResultForArray(array);
}
3340cookie-checkOptimized rows in javascript