I\'m trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting wit
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};