loading...

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

Collapse
kespri profile image
kespri

Swift solution :

let keys: [String:String] = [
    "1":".,?!",
    "2":"abc",
    "3":"def",
    "4":"ghi",
    "5":"jkl",
    "6":"mno",
    "7":"pqrs",
    "8":"tuv",
    "9":"wxyz",
    "*":"'-+=",
    "0":" ",
    "#":""]

func sendMessage(message: String) -> String {
    var isUpperCaseMode: Bool = false
    var keyPressed: String = ""

    let fetchCharacter: (Character) -> String  = { char in

        guard (keys.index(forKey: .init(char)) == nil) else {
          return "\(char)-"
        }

        guard let key = (keys.first { $1.contains(char.isLetter ? .init(char.lowercased()) : char) }?.key),
            let buttonText = keys[key] else {
                return ""
        }

        var code: [String] = []

        if key == keyPressed && char.isLowercase != isUpperCaseMode{
            code.append("  ")
        }

        keyPressed = key

        guard !char.isWhitespace else {
            code.append(key)
            return code.joined()
        }

        let number = buttonText.distance(from: buttonText.startIndex, to: buttonText.firstIndex(of: .init(char.lowercased())) ?? buttonText.startIndex) + 1

        if char.isLowercase == isUpperCaseMode {
            code.append("#")
            isUpperCaseMode.toggle()
        }

        code.append(String(repeating: key, count: number))
        return code.joined()
    }

    return message.map(fetchCharacter).joined()
}

sendMessage(message:"Def Con 1!") // "#3#33 3330#222#666 6601-1111"
sendMessage(message:"hey") // "4433999"
sendMessage(message:"one two three") // "666 6633089666084477733 33"
sendMessage(message:"Hello World!") // "#44#33555 5556660#9#66677755531111"