Created
January 10, 2022 07:27
-
-
Save BenDMyers/b6a0bd3f3a6474a6a25fac3fd4f39652 to your computer and use it in GitHub Desktop.
RWC: Cap Permutations
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
/** | |
* Gets all possible capitalizations of the given string | |
* @param {string} str string to get capitalization permutations of | |
* @returns {string[]} list of all possible capitalization of the given string | |
*/ | |
function capPermutations(str) { | |
let characters = str.split(''); | |
let permutations = ['']; | |
for (let character of characters) { | |
// Character isn't a capitalizable letter, so tack it on to all visited permutations so far | |
if (character.toUpperCase() === character.toLowerCase()) { | |
permutations = permutations.map(perm => `${perm}${character}`); | |
} else { // Character is a letter, so get all uppercase and lowercase permutations | |
const permutationsWithLowercase = permutations.map(perm => `${perm}${character.toLowerCase()}`); | |
const permutationsWithUppercase = permutations.map(perm => `${perm}${character.toUpperCase()}`); | |
permutations = [...permutationsWithLowercase, ...permutationsWithUppercase]; | |
} | |
} | |
return permutations; | |
} | |
console.log(capPermutations('ab2')); | |
console.log(capPermutations('35p')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment