Skip to content

Instantly share code, notes, and snippets.

@eliashussary
Last active February 22, 2017 13:59
Show Gist options
  • Save eliashussary/fa78b5b0ce01f3394e358613778ec449 to your computer and use it in GitHub Desktop.
Save eliashussary/fa78b5b0ce01f3394e358613778ec449 to your computer and use it in GitHub Desktop.
A function to convert letters into a phone number sequence.
/**
* A function to convert letters into a phone number sequence.
* @param {string} searchStr - String of letters to convert into a phone number sequence.
* @returns {number} The String of letters converted into phone number sequence.
*/
function lettersToPhoneNumber(searchStr) {
// convert lowercase string to uppercase since we compare against uppercase;
// then split string into an array of letters;
searchStr = searchStr.toUpperCase().split('')
// create virtual keypad, associating alpha characters with a single digit;
const keyPads = [{
alpha: ['A', 'B', 'C'],
digit: 2
}, {
alpha: ['D', 'E', 'F'],
digit: 3
}, {
alpha: ['G', 'H', 'I'],
digit: 4
}, {
alpha: ['J', 'K', 'L'],
digit: 5
}, {
alpha: ['M', 'N', 'O'],
digit: 6
}, {
alpha: ['P', 'Q', 'R', 'S'],
digit: 7
}, {
alpha: ['T', 'U', 'V'],
digit: 8
}, {
alpha: ['W', 'X', 'Y', 'Z'],
digit: 9
}, {
alpha: [' '],
digit: 0
}]
// declare our results as an array;
let result = []
// iterate over each letter of the string
searchStr.forEach(letter => {
// filters the virtual keypads for the current letter;
// since we're creating a single digit array,
// we immediately select [0].digit to return the digit corresponding with the letter;
let digit = keyPads.filter(keyPad => keyPad.alpha.indexOf(letter) > -1)[0].digit
// using the spread operator, we concatenate a new array;
result = [ ...result, digit]
})
// we return the numbers as a number using the Array.prototype.join method nested within parseInt;
return parseInt(result.join(''))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment