JSFiddle - React, Tailwind, and code Playground
by stchangg
JavaScript
function printCombos(nums, index, word) {
var j;
var places = 3;
var letter;
if (nums[index] <= 1) {
places = 1;
}
if (index >= nums.length) {
words.push(word);
return;
}
for (j = 1; j <= places; j++) {
letter = getCharKey(nums[index], j);
printCombos(nums, index + 1, word + letter);
}
}
function getCharKey(telephoneKey, place) {
var offset = 'A'.charCodeAt(0);
var placeOffset = 1;
var code;
if (telephoneKey <= 1) {
return telephoneKey;
}
if (telephoneKey > 7 || telephoneKey === 7 && place > 1) {
placeOffset = 0;
}
code = offset + 3 * (telephoneKey - 2) + (place - placeOffset);
return String.fromCharCode(code);
};
function debug(str) {
document.write(str + "<br/>");
}
var nums = [1, 2, 0];
var words = [];
printCombos(nums, 0, "");
debug(words.join("\n"));