Created
November 29, 2021 18:03
-
-
Save wdj82/200917a22770bebc680d9ec2713cd54e to your computer and use it in GitHub Desktop.
question for issue #224 of rendezvous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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