Skip to content

Instantly share code, notes, and snippets.

@danedavid
Created May 2, 2018 16:59
Show Gist options
  • Save danedavid/cb5db5a77f37ef1f1021057a51d240b2 to your computer and use it in GitHub Desktop.
Save danedavid/cb5db5a77f37ef1f1021057a51d240b2 to your computer and use it in GitHub Desktop.
Permutations of a String in JavaScript
// returns an array containing all permutations of a given string
const permute = str => {
let permutations = [];
if ( str.length <= 1 ) {
return [str];
}
for ( let i = 0; i < str.length; i++ ) {
let char = str[i];
// if more than one occurence of the character
if ( str.indexOf(char) !== i ) {
continue;
}
let restOfString = str.slice(0, i) + str.slice(i + 1);
permute(restOfString).forEach(item => {
permutations.push(char + item);
});
}
return permutations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment