Issue
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);
}
});
});
Solution
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');
Answered By - Tushar Shahi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.