LESS - Create ID by looping through two variables

2019-09-18 06:26发布

问题:

I am trying to create a loop that outputs all of the possible combinations between coordinates -2,-2 to 2,2. Is there any way to do this without creating multiple loops?


Desired Output

#p1x0,#p2x0,#p-1x0,#p-2x0,#p1x1,#p-1x-1,#p-1x1,#p1x-1,#p2x2,#p-2x-2,p2x-2,p-2x2,#p2x1,#p2x-1,#p1x2,#p1x-2,#p-2x1,#p-2x-1,#p-1x2,#p-1x-2,#p0x-1,#p0x-2,#p0x0,#p0x1,#p0x2{}

Current Attempt

#cube-side {
border:red;
}

.create-cubes(@n, @i: -2, @z: -2, @side-sum:@i + @z) when (@side-sum =< @n) {
    & when (@i < @z) {
        .create-cubes(@n, @i+1);
    }
    & when (@z < @i) {
        .create-cubes(@n, @z+1);
    }
    #p@{i}x@{z}:extend(#cube-side) {}
}

.create-cubes(4);

Output

#cube-side,
#p-2x-2 {
  border: red;
}

回答1:

There's way to do this w/o any loops at all:

#cube-side {
    border: red;
}

-2, -1, 0, 1, 2 {
    #p&x&:extend(#cube-side) {}
}

Though for an arbitrary list of values just a nested loop is the simplest solution of course (see for example), e.g. (in "pure Less") something like:

.create-cubes(-2, 2);
.create-cubes(@min, @max) {
    .i; .i(@i: @min) when (@i <= @max) {
        .j; .i(@i + 1);
    }
    .j(@j: @min) when (@j <= @max) {
        #p@{i}x@{j}:extend(#cube-side) {}
        .j(@j + 1);
    }
}