Last active
July 8, 2020 16:40
-
-
Save bcamargogui/f0b7994d5882ed7cb5e5d73e3bb426c1 to your computer and use it in GitHub Desktop.
This file contains 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 getStringPermutation(letters = '') { | |
const lettersLength = letters.length; | |
// not able to permut | |
if (lettersLength < 2) return letters; | |
// break letters to array | |
const lettersParts = letters.split(''); | |
// only option to permut | |
if (lettersLength === 2) { | |
// reverse letters order string | |
const reversedLetters = lettersParts.reverse().join(''); | |
// return current order and reversed order | |
return new Array(letters).concat(new Array(reversedLetters)); | |
} | |
// when lettersLength > 3 | |
// divide reducer to better learn | |
function reducer(accumulated, letter, index) { | |
// get partial string to permut | |
const toPermut = letters.slice(0, index) + letters.slice(index + 1); | |
// get array of permutations | |
const permuted = getStringPermutation(toPermut); | |
// add current letter to start of each permutation | |
const toConcat = permuted.map(val => letter + val); | |
// concat to array of options to return later | |
return accumulated.concat(toConcat); | |
} | |
// execute reducer | |
return lettersParts.reduce(reducer, []); | |
} | |
const toPermut = 'abc'; | |
console.log(getStringPermutation(toPermut)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment