Skip to content

Instantly share code, notes, and snippets.

@spenserfiller
Created October 26, 2015 14:33
Show Gist options
  • Select an option

  • Save spenserfiller/0a330134bfd7d85a75fa to your computer and use it in GitHub Desktop.

Select an option

Save spenserfiller/0a330134bfd7d85a75fa to your computer and use it in GitHub Desktop.
Get all permutations for a string in JS
var getPermutationsFor = function(string){
var everythingButFirstLetter, results;
results = [];
if(string.length === 1){
results.push(string)
}else{
string.split('').forEach(function(firstLetter, index, array){
everythingButFirstLetter = array.slice(0,index).concat(array.slice(index+1)).join('');
results.push(getPermutationsFor(everythingButFirstLetter)
.map(function combinePermutationsWithFirstLetter(secondHalfOfPermutation){
return firstLetter+secondHalfOfPermutation
})
)
})
}
return [].concat.apply([], results)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment