Algorithm for subdividing html-elements I am trying to write a module that automatically subdivides  div-elements, given some initial parameters.

I've prepared the following jsfiddle.

What I am doing at the moment is:


Setting the width and height of the parent element.
Setting the child elements to float left and assigning percentual width and height to them, based on the specified parameters.




that.createDivisionData = function(paramObj) {

    var 
        numOfDivisions = paramObj.divisions,
        widthTop = paramObj.widthTop,
        heightTop = paramObj.heightTop,
        widthBottom = paramObj.widthBottom,
        widthBlock = paramObj.blockWidth,
        heightBlock = paramObj.blockHeight,
        data = [];

    for ( var i = 1; i &lt;= numOfDivisions; i++) {
        var divisionObj = {};
        if (i &lt; 3) {
            divisionObj.widthPerc = i % 2 ? widthTop + '%' : (100 - widthTop) + '%';
            divisionObj.width = i % 2 ? widthTop * widthBlock / 100 : (100 - widthTop) * widthBlock / 100;
            divisionObj.heightPerc = heightTop + '%';
            divisionObj.height = heightBlock * heightTop / 100;
        } else {
            divisionObj.widthPerc =  i % 2 ? widthBottom + '%' : (100 - widthBottom) + '%';
            divisionObj.width =  i % 2 ? widthBottom * widthBlock / 100 : (100 - widthBottom) * widthBlock / 100;
            divisionObj.heightPerc = (100 - heightTop) + '%';
            divisionObj.height = (100 - heightTop) * heightBlock / 100;
        }
        data.push(divisionObj);
    }        
    return data;
};


The way I am doing it at the moment actually works. But it feels somehow wrong, dirty, unfinished, you name it. I know this is a subjective question, but maybe someone has an idea. How can I do this in a cleaner way?
A lot of what you are doing is repeated code so you should DRY it out.  For instance, widthPerc is the same code except for the values of widthTop and widthBottom. We can also simply all of our checks by setting them up as vars.  So that could be re-written like this:

var isFirstTwo = !!( i &lt; 3 ); // go ahead and just eval once
var isEven = !!( i % 2 ); // go ahead and just evalonce

//which width value do we want?
var widthDir = ( isFirstTwo ) ? widthTop : widthBottom;
//is it an even number?
widthDir = ( isEven ) ? widthDir : 100 - widthDir;
widthBlock = widthDir * widthBlock / 100;  

divisionObj.widthPerc = widthDir +'%';
divisionObj.width = widthBlock;


This reduces a lot of your code.  You could follow a similar technique for height (it's actually easier than width).

var heightTop = ( isEven ) ? heightTop : (100 - heightTop);
var heightBlock =  heightBlock * heightTop / 100
divisionObj.heightPerc = heightTop + '%';
divisionObj.height = heightBlock;


Hope that helps. I have updated the fiddle. Let me know if you have questions or comments.