Skip to content
Advertisement

Find all lowercase and uppercase combinations of a string in Javascript

I am looking for this stackoverflow question to be answered in Javascript.

So if my input is “word”, the function should return:

word, Word, wOrd, WOrd, woRd, WoRd, etc..

here’s what i have so far but it only produces the permutations (doesn’t capitalize anything)

var perm = function(str){
var results = [];

var combos = function(reference, appendTo){
 appendTo = appendTo || "";
 if(reference.length === 0) {
  results.push(appendTo);
 }
 for(var i = 0; i < reference.length; i++){
  var current = reference.splice(i, 1);
  combos(reference, appendTo+current);
   reference.splice(i, 0, current)
 }
} 
combos(str.split(""));
return results;
}
perm("word");

Advertisement

Answer

One option would be generating capitalization permutations via binary logic.

As a simple example of the snippet below, consider the following table where the left column is the binary representation of the current permutation and the right column is the resulting capitalization:

0000 | word
1000 | Word
0100 | wOrd
1100 | WOrd
...
1111 | WORD

// Used to display the results
const write = (msg) => {
  document.body.appendChild(document.createElement('div')).innerHTML = msg;
};

const input = "word";
const letters = input.split("");
const permCount = 1 << input.length;

for (let perm = 0; perm < permCount; perm++) {
  // Update the capitalization depending on the current permutation
  letters.reduce((perm, letter, i) => {
    letters[i] = (perm & 1) ? letter.toUpperCase() : letter.toLowerCase();
    return perm >> 1;
  }, perm);

  const result = letters.join("");
  write(result);
}

Note that theoretically this approach would work all the way up to Number.MAX_SAFE_INTEGER, up to inputs of length 52, but realistically you’ll run into performance issues.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement