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)
JavaScript
x
19
19
1
var perm = function(str){
2
var results = [];
3
4
var combos = function(reference, appendTo){
5
appendTo = appendTo || "";
6
if(reference.length === 0) {
7
results.push(appendTo);
8
}
9
for(var i = 0; i < reference.length; i++){
10
var current = reference.splice(i, 1);
11
combos(reference, appendTo+current);
12
reference.splice(i, 0, current)
13
}
14
}
15
combos(str.split(""));
16
return results;
17
}
18
perm("word");
19
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:
JavaScript
1
7
1
0000 | word
2
1000 | Word
3
0100 | wOrd
4
1100 | WOrd
5
6
1111 | WORD
7
JavaScript
1
19
19
1
// Used to display the results
2
const write = (msg) => {
3
document.body.appendChild(document.createElement('div')).innerHTML = msg;
4
};
5
6
const input = "word";
7
const letters = input.split("");
8
const permCount = 1 << input.length;
9
10
for (let perm = 0; perm < permCount; perm++) {
11
// Update the capitalization depending on the current permutation
12
letters.reduce((perm, letter, i) => {
13
letters[i] = (perm & 1) ? letter.toUpperCase() : letter.toLowerCase();
14
return perm >> 1;
15
}, perm);
16
17
const result = letters.join("");
18
write(result);
19
}
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.