Javascript String permutations() method

Description

Javascript String permutations() method


String.prototype.permutations = function () {
  const baseString = this/*from  w w w .  j av  a 2 s. c  om*/

  const generatePermutations = (availableLetters, usedLetters = '') => {
    if (!availableLetters) {
      permutations.push(usedLetters)
    } else {
      for (let i = 0; i < availableLetters.length; i++) {
        const remainingLetters = availableLetters.slice(0, i) + availableLetters.slice(i + 1)
        generatePermutations(remainingLetters, usedLetters + availableLetters[i])
      }
    }
  }

  let permutations = []
  generatePermutations(baseString)
  return permutations
}

const x = 'CAT'
console.log(x.permutations())



PreviousNext

Related