Created
October 20, 2019 15:29
-
-
Save dmjcomdem/5415921ddf2118f69f76757e2e296107 to your computer and use it in GitHub Desktop.
Generates all permutations of a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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