forked from TheOdinProject/javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations-solution.js
More file actions
25 lines (21 loc) · 924 Bytes
/
permutations-solution.js
File metadata and controls
25 lines (21 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const permutations = function (array, index = 0, results = []) {
if (index == array.length) {
// We have formed a valid permutation.
// the [...array] syntax is a way to clone the contents of the array.
// because we do not want to pass a reference to the array, as that would mean
// that each item in `results` will be the same item
results.push([...array]);
return results;
}
for (let i = index; i < array.length; i++) {
// We use "destructuring assignment" here to swap the values of array[index] and array[i]
//
// More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
[array[index], array[i]] = [array[i], array[index]];
permutations(array, index + 1, results);
[array[index], array[i]] = [array[i], array[index]];
}
return results;
};
// Do not edit below this line
module.exports = permutations;