Home > OS >  Angular typescript : How to optimize for loop inside for loop
Angular typescript : How to optimize for loop inside for loop

Time:11-02

I have a nasted loop, I wish to optimize the iteration and comparisons, can it be done?

How do I optimize my logic shown below and use map, reduce, filter to avoid so many lines of code and loops and to use

fill() {
   this.rolesPermiAdd = [];
   this.rolPermiRemove = [];
   this.arrayRAndPern.subscribe((data: any) => {

     for (let i = 0; i < this.permissions.length; i  ) {
       this.rolePermiCheck[i] = new Array();
       for (let j = 0; j < this.roles.length; j  ) {
         this.rolPermi.find(element => {
           if ((element.permission === this.permissions[i].code) && (element.role === this.roles[j].code)) {
             this.rolePermiCheck[i][j] = true;
           }
         });
       }
     }
   })
 }```

CodePudding user response:

Well in this kind of situation, you have to use Map or Set because these data structures have O(1) in retrieving data. I didn't know your exact data model, but I have made this sample to show the difference between Set and Array. The method func1 is using Set and func2 is your sample code. The difference between them is about 90 times.

func1 = (number) => {
  const d1 = new Date();
  var permissions = [];
  var roles = [];

  for (let i = 0; i < number; i  ) {
    permissions.push({ code: i });
    roles.push({ code: i });
  }

  var rolePermissionCheck = [];

  var set = new Set();

  for (const role of roles) {
    for (const permission of permissions) {
        set.add(`${role}_${permission}`);
    }
  }

  for (let i = 0; i < permissions.length; i  ) {
    rolePermissionCheck[i] = new Array();
    for (let j = 0; j < roles.length; j  ) {
      rolePermissionCheck[i][j] = set.has(`${roles[j]}_${permissions[i]}`);
    }
  }
  const d2 = new Date();

  console.log(d2 - d1);
};

func2 = (number) => {
  const d1 = new Date();
  var permissions = [];
  var roles = [];
  var rolesPermissions = [];

  for (let i = 0; i < number; i  ) {
    permissions.push({ code: i });
    roles.push({ code: i });
  }

  var rolePermissionCheck = [];

  for (const role of roles) {
    for (const permission of permissions) {
      rolesPermissions.push({ permission, role });
    }
  }

  for (let i = 0; i < permissions.length; i  ) {
    rolePermissionCheck[i] = new Array();
    for (let j = 0; j < roles.length; j  ) {
      rolesPermissions.find((element) => {
        if (
          element.permission === permissions[i].code &&
          element.role === roles[j].code
        ) {
          rolePermissionCheck[i][j] = true;
        }
      });
    }
  }

  const d2 = new Date();

  console.log(d2 - d1);
};

func1(100); // 21
func2(100); //1804
  • Related