Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I minify the following series of for loops into a less compact code?

I have the following code which follows a pattern of loops , I have a feeling that code can be minified to a recursion like code or any less ugly looking code , but I am unable to figure it out.

I want to run six loops one inside the other from 1000 to 10000 in javascript, I look to minify the code if possible.

I am beginner in coding , but all kinds of methods are acceptable for me.

I am updating the code as previous code might get ambigous for some users.

function dummyFunc(x,y){
    if( some logic for x == some logic for y){
         return true;
    }
    return false;
}

for(var i = 1000;i < 10000;i++){
  for(var j = 1000;j < 10000;j++){
    if(dummyFunc(i,j)){
      for(var k = 1000;k < 10000;k++){
        if(dummyFunc(j,k)){
          for(var l = 1000;l < 10000;l++){
            if(dummyFunc(k,l)){
              for(var m = 1000;m < 10000;m++){
                if(dummyFunc(l,m)){
                  for(var n = 1000;n < 10000;n++){
                     if(dummyFunc(m,n)){
                        break;
                     }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
like image 911
R K Avatar asked Oct 21 '18 12:10

R K


Video Answer


1 Answers

You could extract the for loop into a function:

 function range(start, end, callback) {
   for(let i = start, start < end, i++)
     callback(i);
 }

That can be used as:

 range(1000, 10000, i => {
   range(1000, 10000, j => {
     range(1000, 10000, k => {
       range(1000, 10000, l => {
        range(1000, 10000, m => {
          range(1000, 10000, n => {
            console.log(i, j, k, l, m, n);
         });
       });
     });
   });
 });

To simplify that even further, you could use a generator that yields an array of values which you can destructured:

  function* ranges(start, end, repeats) {
    if(repeats > 1) {
      for(const values of ranges(start, end, repeats - 1)) {
         for(const value of ranges(start, end, 0)) {
             yield values.concat(value);
         }
      }
    } else {
      for(let i = start; i < end; i++) 
        yield [i];
   }
}

That can be used as:

  for(const [i, j, k, l, m, n] of ranges(1000, 10000, 6)) {
     console.log(i, j, k, l, m, n);
  }
like image 112
Jonas Wilms Avatar answered Sep 23 '22 04:09

Jonas Wilms