user3068590 user3068590 - 25 days ago 15
Javascript Question

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");

Nit Nit
Answer

It's as simple as generating permutations in any language with binary logic.

var s = "word";
var sp = s.split("");
for (var i = 0, l = 1 << s.length; i < l; i++) {
  for (var j = i, k = 0; j; j >>= 1, k++) {
    sp[k] = (j & 1) ? sp[k].toUpperCase() : sp[k].toLowerCase();
  }
  var st = sp.join("");
  var d = document.createElement("p");
  d.appendChild(document.createTextNode(st));
  document.body.appendChild(d);
}

Comments