Skip to content

Instantly share code, notes, and snippets.

@BenDMyers
Created January 10, 2022 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenDMyers/b6a0bd3f3a6474a6a25fac3fd4f39652 to your computer and use it in GitHub Desktop.
Save BenDMyers/b6a0bd3f3a6474a6a25fac3fd4f39652 to your computer and use it in GitHub Desktop.
RWC: Cap Permutations
/**
* 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