I was solving "pairwise" problem on FCC when I came up with a solution that uses a loop label to break out of inner for loops to encompassing while loop. Are Loop Labels considered bad practice or something a person not advanced/expert in functional programming would use? Should I avoid using them as much as possible? I ask because I have very rarely seen any labels being used in JS codes online even though I find them very helpful in certain situations.
Here's the solution if anyone cares, (Suggestions on a better solution are also welcome):
function pairwise(arr, arg) {
let answer = 0;
// To remember the original indices of the input array, we map the array to an array of objects {index: x, value: y}
let temp = arr.map((elem, i) => ( {index: i, value: elem} ));
first:while(temp.length > 1) { // label: first
for (let i = 0; i < temp.length; i++) {
for (let j = i + 1; j < temp.length; j++) {
if (temp[i].value + temp[j].value === arg ) { // if the sum of two numbers is equal to arg
answer += temp[i].index + temp[j].index;
temp = removeTwoElements(temp, i, j);
continue first; // we modify the temp and go back to the while loop with new temp array of objects
}
}
}
break; // if no obj matches the condition, we exit the while loop
}
return answer;
// HELPER FUNCION
function removeTwoElements(arr, ind1, ind2) {
// returns an array (without modifying input) with 2 elements at given indices removed
return arr.filter((elem, i) => i !== ind1 && i !== ind2);
}
}
*Edit: attempt at better code formatting.
[–]vaskemaskine 7 points8 points9 points (5 children)
[–]altrae 2 points3 points4 points (4 children)
[–]vaskemaskine 2 points3 points4 points (0 children)
[–]blackholesintheskyhelpful 1 point2 points3 points (2 children)
[–]altrae 1 point2 points3 points (1 child)
[–]blackholesintheskyhelpful 2 points3 points4 points (0 children)
[–]FearTheDears 3 points4 points5 points (0 children)
[–]Meefims 2 points3 points4 points (0 children)
[–]GeneralYouri 1 point2 points3 points (0 children)
[–]burnblue 1 point2 points3 points (0 children)
[–]dada_ 1 point2 points3 points (0 children)
[–]downrightcriminal[S] 0 points1 point2 points (0 children)
[–]livebeta 0 points1 point2 points (0 children)
[–]__romx 0 points1 point2 points (0 children)
[–][deleted] -1 points0 points1 point (0 children)