Skip to content

Instantly share code, notes, and snippets.

@wdj82
Created November 29, 2021 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wdj82/200917a22770bebc680d9ec2713cd54e to your computer and use it in GitHub Desktop.
Save wdj82/200917a22770bebc680d9ec2713cd54e to your computer and use it in GitHub Desktop.
question for issue #224 of rendezvous
const keypad = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z'],
};
function phoneLetters(numberString) {
if (typeof numberString !== 'string' || !numberString.match(/^[2-9]+$/)) {
throw new Error('input must be a string of only numbers between 2 and 9');
}
const numbersArray = numberString.split('');
if (numbersArray.length === 1) {
return keypad[numbersArray];
}
const lettersArray = numbersArray.map((number) => keypad[number]);
const answer = lettersArray.reduce(
(combinations, newLetters) => {
return (
combinations
.map((prev) => {
// for each new letter combine to each previous combination
return newLetters.map((letter) => {
return prev.concat(letter);
});
})
// combine all the new combinations into a single array
// for the next group of new letters
.reduce((a, b) => {
return a.concat(b);
}, [])
);
},
[[]],
);
return answer.map((letters) => letters.join(''));
}
console.log(phoneLetters('9'));
console.log(phoneLetters('23'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment