How to concatenate operators in javascript?

Viewed 48

I am writing next_previous() function for pagination purpose, I have for loop which is moving from 0 to the given length. I want to use the same loop for two cases from 0 to 10 and from 10 to 0.

for (var i = 0; i < 10; i++) {
}

for (var i = 10; i > 0; i--) {
}

to use both cases in one loop I am doing something like this but not working

var  i = 0; a = '', b = '';

if(somevar === true){
   i = 0 , a = '++', var b = '<';
}else{
   i = 10 , a = '--', var b = '>';
}

for (i; i +b+ 0; i+a) {
} 

now problem is javascript not allowing concatenation this way, how can I achieve this?

See screenshot

4 Answers

Try this approach which uses for the logic part ( increment and condition ) functions.

ES6

let i = 0;
let a;
let b;
let count = 0;

let somevar = true;

if(somevar) {
   i = 0;
   count = 10;
   a = () => i++;
   b = () => i < count;
} else {
   i = 10;
   count = 0;
   a = () => i--;
   b = () => i > count;
}

for (; b(); a()) {
   console.log(i);
}

ES5

var i = 0;
var a;
var b;
var count = 0;

var somevar = true;

if(somevar) {
   i = 0;
   count = 10;
   a = function() { i++; };
   b = function() { return i < count; };
} else {
   i = 10;
   count = 0;
   a = function() { i--; };
   b = function() { return i > count; };
}

for (; b(); a()) {
   console.log(i);
}

It seems like you are looking for an eval solution, but this really is not how one would approach this problem. Rather go for a functional design:

function forward(cb) {
    for (var i = 0; i < 10; i++) cb(i);
}
function backward(cb) {
    for (var i = 10; i > 0; i--) cb(i);
}

const loop = somevar ? forward : backward;
loop(i => {
    …
});

Just use eval(i+b+10) instead of i+b+10

Related