JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//wzrd.in/standalone/expect@latest"></script>
<script src="//wzrd.in/standalone/deep-freeze@latest"></script>
<body>
</body>
JavaScript
const permutations = function*(elements) {
if (elements.length === 1) {
yield elements;
} else {
let [first, ...rest] = elements;
for (let perm of permutations(rest)) {
for (let j = 0; j < elements.length; j++) {
let start = perm.slice(0, j);
let rest = perm.slice(j);
yield [...start, first, ...rest];
}
}
}
}
const testPermutations = () => {
expect(Array.from(permutations([1, 2, 3])))
.toEqual([
[1, 2, 3],
[2, 1, 3],
[2, 3, 1],
[1, 3, 2],
[3, 1, 2],
[3, 2, 1]
]);
};
const logdisp = (arg) => {
document.querySelector('body').innerHTML = arg;
console.log(arg)
};
testPermutations();
logdisp('All tests passed');