Skip to content

Instantly share code, notes, and snippets.

@dmjcomdem
Created October 20, 2019 15:29
Show Gist options
  • Save dmjcomdem/5415921ddf2118f69f76757e2e296107 to your computer and use it in GitHub Desktop.
Save dmjcomdem/5415921ddf2118f69f76757e2e296107 to your computer and use it in GitHub Desktop.
Generates all permutations of a string
function stringPermutations (str) {
if (str.length <=2) {
return str.length === 2 ? [str, str[1] + str[0]] : [str];
}
return [...str].reduce((acc, letter, i) => {
const letters = str.slice(0, i) + str.slice(i + 1);
const transformString = stringPermutations(letters).map(item => letter + item);
return [...acc, ...transformString];
}, []);
}
stringPermutations('abc'); // ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment