-
Notifications
You must be signed in to change notification settings - Fork 0
/
decodeMorse.js
34 lines (31 loc) · 1 KB
/
decodeMorse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
decodeMorse = function(morseCode){
let result = '';
let currentLetter = '';
let i = 0;
morseCode = morseCode.trim();
while (i < morseCode.length) {
if (morseCode[i] !== ' ') {
// Build up the current Morse code letter
currentLetter += morseCode[i];
i++;
// If we're at the end, decode the last letter
if (i === morseCode.length && currentLetter !== '') {
result += MORSE_CODE[currentLetter];
}
} else {
// We've hit a space, time to decode the current letter
if (currentLetter !== '') {
result += MORSE_CODE[currentLetter];
currentLetter = '';
}
// Check if it's the end of a word (three spaces)
if (morseCode[i + 1] === ' ' && morseCode[i + 2] === ' ') {
result += ' '; // Add space to separate words
i += 3; // Skip the three spaces
} else {
i++; // Skip the single space
}
}
}
return result;
}