loading...

Discussion on: Daily Challenge #217 - SMS w/ an Old Phone

Collapse
mellen profile image
Matt Ellen

Brute force the key map!

const keymap = new Map(
  [
    ['0', '0-'],
    ['1', '1-'],
    ['2', '2-'],
    ['3', '3-'],
    ['4', '4-'],
    ['5', '5-'],
    ['6', '6-'],
    ['7', '7-'],
    ['8', '8-'],
    ['9', '9-'],
    ['a', '2'],
    ['b', '22'],
    ['c', '222'],
    ['d', '3'],
    ['e', '33'],
    ['f', '333'],
    ['g', '4'],
    ['h', '44'],
    ['i', '444'],
    ['j', '5'],
    ['k', '55'],
    ['l', '555'],
    ['m', '6'],
    ['n', '66'],
    ['o', '666'],
    ['p', '7'],
    ['q', '77'],
    ['r', '777'],
    ['s', '7777'],
    ['t', '8'],
    ['u', '88'],
    ['v', '888'],
    ['w', '9'],
    ['x', '99'],
    ['y', '999'],
    ['z', '9999'],
    [' ', '0'],
    ['.', '1'],
    [',', '11'],
    ['?', '111'],
    ['!', '1111'],
    ['*', '*-'],
    ['\'', '*'],
    ['-', '**'],
    ['+', '***'],
    ['=', '****'],
    ['#', '#-'],
  ]);

function sendMessage(msg)
{
  let keypresses = '';
  let isUppercaseMode = false;
  let lastKey = '--';
  for(let c of msg)
  {
    let currKey = keymap.get(c.toLowerCase());
    if(isUppercaseMode && c.toUpperCase() != c)
    {
      keypresses += '#';
      isUppercaseMode = false;
    }
    else if(!isUppercaseMode && c.toLowerCase() != c)
    {
      keypresses += '#';
      isUppercaseMode = true;
    }
    else if(lastKey[1] !== '-' && currKey[0] === lastKey[0])
    {
      keypresses += ' ';
    }

    lastKey = currKey;

    keypresses += currKey;
  }
  return keypresses;
}