|
1 | 1 | /** |
2 | 2 | * @param {*[]} permutationOptions |
| 3 | + * @param {number} permutationLength |
| 4 | + * @param {*[]} currentPermutation |
| 5 | + * @param {*[][]} permutations |
3 | 6 | * @return {*[]} |
4 | 7 | */ |
5 | 8 | export default function permutateWithRepetitionsRecursive( |
6 | | - options, |
7 | | - n = options.length || 0, |
8 | | - prefix = [], |
9 | | - perms = [], |
| 9 | + permutationOptions, |
| 10 | + permutationLength = permutationOptions.length || 0, |
| 11 | + currentPermutation = [], |
| 12 | + permutations = [], |
10 | 13 | ) { |
11 | | - // If initial options are null or empty then return empty array |
12 | | - if (!options || !options.length) return []; |
| 14 | + // If initial options are null or empty then return empty array. |
| 15 | + if (!permutationOptions || !permutationOptions.length) { |
| 16 | + return []; |
| 17 | + } |
| 18 | + |
| 19 | + // If no more iterations required then add current permutation to permutations array. |
| 20 | + if (permutationLength === 0) { |
| 21 | + permutations.push(currentPermutation); |
13 | 22 |
|
14 | | - // If no more iterations then add current prefix to perms array |
15 | | - if (n === 0) { |
16 | | - perms.push(prefix); |
17 | | - return perms; |
| 23 | + return permutations; |
18 | 24 | } |
19 | 25 |
|
20 | | - // Recursively find permutations and store in perms array |
21 | | - options.forEach((option) => { |
22 | | - permutateWithRepetitionsRecursive(options, n - 1, prefix.concat([option]), perms); |
| 26 | + // Recursively find permutations and store in permutations array. |
| 27 | + permutationOptions.forEach((permutationOption) => { |
| 28 | + permutateWithRepetitionsRecursive( |
| 29 | + permutationOptions, |
| 30 | + permutationLength - 1, |
| 31 | + currentPermutation.concat([permutationOption]), |
| 32 | + permutations, |
| 33 | + ); |
23 | 34 | }); |
24 | 35 |
|
25 | | - return perms; |
| 36 | + return permutations; |
26 | 37 | } |
0 commit comments