T9 Spelling

The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters. The letters are mapped onto the digits as shown below. To insert the character B for instance, the program would press 22. In order to insert two characters in sequence from the same key, the user must pause before pressing the key a second time. The space character ‘ ‘ should be printed to indicate a pause. For example, 2 2 indicates AA whereas 22 indicates B.

For each test case, output one line containing “Case #x: ” followed by the message translated into the sequence of keypresses.

Input Output
4
hi
yes
foo  bar
hello world
Case #1: 44 444
Case #2: 999337777
Case #3: 333666 6660 022 2777
Case #4: 4433555 555666096667775553

Solution:

#!/usr/local/bin/node
const readline = require('readline')
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
})
const letters = {
	' ': '0',
	'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'
}
const string_to_t9 = (str) => {
	if (str.length < 1 || str.length > 1000) return
	let result = ''
	for (let i = 0; i < str.length; i++) {
		if (letters[ str[i] ] && letters[ str[i] ][0] === result[ result.length - 1 ]) result += ' '
		result += letters[ str[i] ] ? letters[ str[i] ] : str[i]
	}
	return result
}
let case_counter = 0
rl.on('line', (input) => {
	let r = string_to_t9(input)
	if (r != null && r !== input)
		console.log(`Case #${++case_counter}: ${r}`)
})

Output:

chmod +x t9.js
./t9.js < C-small-practice.in > small.out
./t9.js < C-large-practice.in > large.out

Test: