loading...

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

Collapse
mushtaqasif profile image
mushtaqasif

JS Solution

const sendMessage = message => {
    const keys = ['0', '1', '2', '3', '4','5', '6', '7', '8', '9', 
        '*', '#'];

    const keyCharacterMap = [' ', '.,?!', 'abc', 'def', 'ghi' , 'jkl', 
        'mno', 'pqrs', 'tuv', 'wxyz', '\'-+='];

    let result = [];
    let caseToggle = false;
    let previousKey = null;
    let caseToggleKey = keys[11];

    for (const character of message.split('')) {
        if (keys.indexOf(character) > -1) {
            result.push(character + '-');
            previousKey = null
        } else {
            for (const characterSet of keyCharacterMap) {
                let index = characterSet.indexOf(character.toLowerCase());
                let key = keys[keyCharacterMap.indexOf(characterSet)];
                let isUpperCase = character !== character.toLowerCase();

                if (index > -1) {
                    let caseToggleResult = '';

                    if (
                        (isUpperCase && !caseToggle) 
                        || (!isUpperCase && caseToggle)
                    ) {
                        caseToggle = !caseToggle;
                        caseToggleResult = caseToggleKey;
                        previousKey = null;
                    } 

                    result.push((key == previousKey ? ' ' : '')
                        + caseToggleResult + key.repeat(index + 1));

                    previousKey = key;

                    break;
                }
            }
        }
    }

    return result.join('');
};

[
    "Def Con 1!",
    "hey",
    "one two three",
    "Hello World!",
].forEach(s => console.log(
    `"${s}" => "${sendMessage(s)}"`
));

output:

"Def Con 1!" => "#3#33 3330#222#666 6601-1111"
"hey" => "4433999"
"one two three" => "666 6633089666084477733 33"
"Hello World!" => "#44#33555 5556660#9#66677755531111"