I am trying to optimize this function that I found online.
Example input: [1, 2, 3]
Example output: [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Here's the code:
const combinations = arr => {
let parentValue = [];
let cursor = 0;
for (const parentThis of arr) {
const value = [[parentThis]];
for (const thiss of parentValue) {
value.push(thiss.concat([parentThis]));
}
parentValue = parentValue.concat(value);
}
return parentValue;
};
(the variable names are weird because I'm running this as a MongoDB aggregation)
Running this 10k times on an array of 10 elements takes about 23 seconds. How can I make it run faster? I am open to some tradeoffs.
An obvious improvement I found is to decrease the amount of elements. Running it 10k times on an array of 9 elements takes 9 seconds.
I suspect another improvement would be to reject some outputs before they are generated (single-element combinations and the all-elements combination might not be too useful), but I can't figure out how to put this into code.
I tried to improve by removing the first iteration (supplying [arr[0]] as the initialValue and starting the outer for loop from the second element) but it doesn't seem to make a significant difference.