Skip to content

Commit e5a06e6

Browse files
committed
Simplify combineWithoutRepetitions function.
1 parent 55ecc0b commit e5a06e6

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,29 @@
11
/**
22
* @param {*[]} comboOptions
33
* @param {number} comboLength
4-
* @param {*[][]} combos
5-
* @param {*[]} currentCombo
64
* @return {*[]}
75
*/
8-
function combineRecursively(comboOptions, comboLength, combos = [], currentCombo = []) {
9-
if (comboLength === 0) {
10-
combos.push(currentCombo);
11-
12-
return combos;
6+
export default function combineWithoutRepetitions(comboOptions, comboLength) {
7+
if (comboLength === 1) {
8+
return comboOptions.map(comboOption => [comboOption]);
139
}
1410

11+
const combos = [];
12+
13+
// Eliminate characters one by one and concatenate them to
14+
// combinations of smaller lengths.s
1515
for (let letterIndex = 0; letterIndex <= (comboOptions.length - comboLength); letterIndex += 1) {
16-
const letter = comboOptions[letterIndex];
17-
const restCombinationOptions = comboOptions.slice(letterIndex + 1);
16+
const currentLetter = comboOptions[letterIndex];
1817

19-
combineRecursively(
20-
restCombinationOptions,
18+
const smallerCombos = combineWithoutRepetitions(
19+
comboOptions.slice(letterIndex + 1),
2120
comboLength - 1,
22-
combos,
23-
currentCombo.concat([letter]),
2421
);
22+
23+
smallerCombos.forEach((smallerCombo) => {
24+
combos.push([currentLetter].concat(smallerCombo));
25+
});
2526
}
2627

2728
return combos;
2829
}
29-
30-
/**
31-
* @param {*[]} combinationOptions
32-
* @param {number} combinationLength
33-
* @return {*[]}
34-
*/
35-
export default function combineWithoutRepetitions(combinationOptions, combinationLength) {
36-
return combineRecursively(combinationOptions, combinationLength);
37-
}

0 commit comments

Comments
 (0)