Home > front end >  convert repeating code into function- JavaScript?
convert repeating code into function- JavaScript?

Time:09-26

Am trying to bind values just to view. my code is working so far. but I'm repeating the same nested forEach 3 times. so Sonarcube will definitely mark it as duplicate. Could someone tell me how to avoid code repetition?

Is there any way to optimize the below repeated codes and convert them as a generic function in JavaScript?

response.mainDish.forEach(element => {
    this.selectedMainDish.forEach(ele => {
        if (ele?.id === element.id) {
            this.bindMainDish.push(ele?.mainDish);
        }
    });
});

response.sideDish1?.forEach(element => {
    this.selectedSideDish1List.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish1.push(ele.sideDish1);
        }
    });
});

response.sideDish2?.forEach(element => {
    this.selectedSideDish2.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish2.push(ele.sideDish2);
        }
    });
});

CodePudding user response:

You can make a generic function using dynamic property names

let functionDoThis = function( mainDish , selectedMainDish, bindMainDish){
response[mainDish]?.forEach(element => {
    this[selectedMainDish]?.forEach(ele => {
        if (ele?.id === element.id) {
            this[bindMainDish]?.push(ele[mainDish]);
        }
    });
});

}

functionDoThis('mainDish', 'selectedMainDish' , 'bindMainDish');
functionDoThis('sideDish1', 'selectedSideDish1List' , 'bindSideDish1');

functionDoThis('sideDish2', 'selectedSideDish2' , 'bindSideDish2');

CodePudding user response:

may besomething like that...

const dish_keys =
[ {dish:'mainDish',  selected:'selectedMainDish',      bind:'bindMainDish'  }
, {dish:'sideDish1', selected:'selectedSideDish1List', bind:'bindSideDish1' }
, {dish:'sideDish2', selected:'selectedSideDish2',     bind:'bindSideDish2' }
]


for (let ({dish,selected,bind} of dish_keys)
  if (response[dish])
    response[dish].forEach(element => 
      this[selected].forEach(ele =>  
        if (ele?.id === element.id)  this[bind].push(ele?[dish]);
    ) );
  • Related