123 lines
2.6 KiB
TypeScript
123 lines
2.6 KiB
TypeScript
// Morse code translation utilities
|
|
|
|
export const MORSE_CODE: Record<string, string> = {
|
|
'A': '.-',
|
|
'B': '-...',
|
|
'C': '-.-.',
|
|
'D': '-..',
|
|
'E': '.',
|
|
'F': '..-.',
|
|
'G': '--.',
|
|
'H': '....',
|
|
'I': '..',
|
|
'J': '.---',
|
|
'K': '-.-',
|
|
'L': '.-..',
|
|
'M': '--',
|
|
'N': '-.',
|
|
'O': '---',
|
|
'P': '.--.',
|
|
'Q': '--.-',
|
|
'R': '.-.',
|
|
'S': '...',
|
|
'T': '-',
|
|
'U': '..-',
|
|
'V': '...-',
|
|
'W': '.--',
|
|
'X': '-..-',
|
|
'Y': '-.--',
|
|
'Z': '--..',
|
|
'0': '-----',
|
|
'1': '.----',
|
|
'2': '..---',
|
|
'3': '...--',
|
|
'4': '....-',
|
|
'5': '.....',
|
|
'6': '-....',
|
|
'7': '--...',
|
|
'8': '---..',
|
|
'9': '----.',
|
|
' ': '/',
|
|
'.': '.-.-.-',
|
|
',': '--..--',
|
|
'?': '..--..',
|
|
'!': '-.-.--',
|
|
'-': '-....-',
|
|
'/': '-..-.',
|
|
'@': '.--.-.',
|
|
'(': '-.--.',
|
|
')': '-.--.-'
|
|
};
|
|
|
|
// Reverse mapping for morse to text
|
|
export const MORSE_TO_TEXT: Record<string, string> = Object.fromEntries(
|
|
Object.entries(MORSE_CODE).map(([key, value]) => [value, key])
|
|
);
|
|
|
|
/**
|
|
* Check if a character is supported in Morse code
|
|
*/
|
|
export function isCharacterSupported(char: string): boolean {
|
|
return char.toUpperCase() in MORSE_CODE;
|
|
}
|
|
|
|
/**
|
|
* Validate if Morse code string is properly formatted
|
|
*/
|
|
export function isValidMorse(input: string): boolean {
|
|
// Valid morse contains only dots, dashes, spaces, and forward slashes
|
|
return /^[.\-\s/]*$/.test(input);
|
|
}
|
|
|
|
/**
|
|
* Convert text to morse code
|
|
* Unsupported characters are silently skipped
|
|
*/
|
|
export function textToMorse(text: string): string {
|
|
return text
|
|
.toUpperCase()
|
|
.split('')
|
|
.map(char => MORSE_CODE[char])
|
|
.filter(code => code !== undefined)
|
|
.join(' ');
|
|
}
|
|
|
|
/**
|
|
* Convert morse code to text
|
|
* Invalid morse codes are replaced with '?'
|
|
*/
|
|
export function morseToText(morse: string): string {
|
|
if (!isValidMorse(morse)) {
|
|
return "";
|
|
}
|
|
|
|
return morse
|
|
.split(' ')
|
|
.map(code => {
|
|
// Handle empty strings (multiple spaces)
|
|
if (code === '') return '';
|
|
// Return the decoded character or '?' for unknown codes
|
|
return MORSE_TO_TEXT[code] || '?';
|
|
})
|
|
.join('');
|
|
}
|
|
|
|
/**
|
|
* Normalize morse code input (remove extra spaces, normalize separators)
|
|
*/
|
|
export function normalizeMorse(input: string): string {
|
|
return input
|
|
.trim()
|
|
.replace(/\s+/g, ' ')
|
|
.replace(/\//g, ' / ');
|
|
}
|
|
|
|
/**
|
|
* Compare two morse code strings with tolerance for spacing differences
|
|
*/
|
|
export function compareMorse(expected: string, actual: string): boolean {
|
|
const normalizedExpected = normalizeMorse(expected);
|
|
const normalizedActual = normalizeMorse(actual);
|
|
return normalizedExpected === normalizedActual;
|
|
}
|