JSFiddle - React, Tailwind, and code Playground
by hescano
JavaScript
console.log(getPermutations("12"));
function getPermutations(string) {
if (string.length <=1) {
return new Set(string);
}
var allCharsExceptLast = string.slice(0, -1);
var lastChar = string[string.length -1];
var permutationsOfAllCharsExceptLast = getPermutations(allCharsExceptLast);
var permutations = new Set();
permutationsOfAllCharsExceptLast.forEach(function(permutationOfAllCharsExceptLast) {
for (var position = 0; position <= allCharsExceptLast.length; position++) {
var permutation = permutationOfAllCharsExceptLast.slice(0, position) + lastChar + permutationOfAllCharsExceptLast.slice(position);
permutations.add(permutation);
}
});
return permutations;
}