bernard
bernard

Reputation: 86

Javascript loop for dynamic variables (and values) from array without eval

i'd like to shorten my code, here is what i want to generate :

left_top = {position:"absolute", xPercent:0, yPercent:0, left:"0%", top:"0%"};
left_center = {position:"absolute", xPercent:0, yPercent:-50, left:"0%", top:"50%"};
left_bottom = {position:"absolute", xPercent:0, yPercent:-100, left:"0%", top:"100%"};

center_top = {position:"absolute", xPercent:-50, yPercent:0, left:"50%", top:"0%"};
center_center = {position:"absolute", xPercent:-50, yPercent:-50, left:"50%", top:"50%"};
center_bottom = {position:"absolute", xPercent:-50, yPercent:-100, left:"50%", top:"100%"};

right_top = {position:"absolute", xPercent:-100, yPercent:0, left:"100%", top:"0%"};
right_center = {position:"absolute", xPercent:-100, yPercent:-50, left:"100%", top:"50%"};
right_bottom = {position:"absolute", xPercent:-100, yPercent:-100, left:"100%", top:"100%"};

And here is how i do it :

var output="";
xPos = ["left", "center", "right"];
yPos = ["top", "center", "bottom"];

for (i=0;i<=2;i++){
    xVal = 50*i;
    for(j=0;j<=2;j++){
        yVal = 50*j;
        eval( xPos[i] + "_" + yPos[j] + " = {position:'absolute', xPercent:" + (-xVal) + ", yPercent:" + (-yVal) + ", left:'" + xVal + "%', top:'" + yVal + "%'}");

    }
}

I know that eval is a bad practice so how should i proceed?

Thanks a lot

Upvotes: 0

Views: 43

Answers (2)

sjahan
sjahan

Reputation: 5950

Why not using a function?

const getStyle = (horizontal, vertical) => ({
  position: 'absolute',
  xPercent: horizontal === 'left' ? 0 : horizontal === 'center' ? -50 : -100,
  yPercent: vertical === 'top' ? 0 : vertical === 'center' ? -50 : -100,
  left: horizontal === 'left' ? '0%' : horizontal === 'center' ? '50%' : '100%',
  top: vertical === 'top' ? '0%' : vertical === 'center' ? '50%' : '100%'
});

const left_top = getStyle('left', 'top');
const left_bottom = getStyle('left', 'bottom')
const center_center = getStyle('center', 'center');
// etc.
console.log(left_top, left_bottom, center_center);

Just be careful that any unexpected value will fallback to right/bottom.

Upvotes: 0

sngregory
sngregory

Reputation: 406

Something like this would work:

    var output = "";
    xPos = ["left", "center", "right"];
    yPos = ["top", "center", "bottom"];

    var getObj = function (x, y) {
        return { position: "absolute", xPercent: x * - 1, yPercent: y * -1, left: x + '%', top: y + '%' };
    }

    var results = {};

    for (i = 0; i <= 2; i++) {
        xVal = 50 * i;
        for (j = 0; j <= 2; j++) {
            yVal = 50 * j;
            var key = xPos[i] + "_" + yPos[j];
            var obj = getObj(xVal, yVal);
            results[key] = getObj(xVal, yVal);


        }
    }

Upvotes: 1

Related Questions