Created
October 26, 2015 14:33
-
-
Save spenserfiller/0a330134bfd7d85a75fa to your computer and use it in GitHub Desktop.
Get all permutations for a string in JS
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
| 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