-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmorseCodeDecoder.js
More file actions
100 lines (90 loc) · 3 KB
/
morseCodeDecoder.js
File metadata and controls
100 lines (90 loc) · 3 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var decodeMorse = function(morseCode) {
// remove white spaces at the start of the string
if(morseCode.search(/\s+/) === 0) {
morseCode = morseCode.replace(/\s+/, '');
}
// remove white space at the end of the string
morseCode = morseCode.replace(/\s+$/, '');
var message = '';
var words = [];
// separate input by words (three spaces)
while( morseCode.search(/(\s){3}/) !== -1 ) {
words.push( morseCode.substring(0, morseCode.search(/(\s){3}/)) );
// then remove the word and whitespace
morseCode = morseCode.substring( (morseCode.search(/(\s){3}/) + 3) );
}
// There should be one word left over
words.push(morseCode);
// loop through words
for(var i = 0; i < words.length; i++) {
var word = words[i];
// separate word into characters (one space)
var characters = word.match(/(\S){1,}/g);
// loop through characters
for (var j = 0; j < characters.length; j++) {
// translate character to english, add to message
message += MORSE_CODE[characters[j]];
};
// add space after word
message += " ";
};
// remove last space
message = message.substring(0, message.length - 1);
// return english string
return message;
};
var MORSE_CODE = { '-.-.--': '!',
'.-..-.': '"',
'...-..-': '$',
'.-...': '&',
'.----.': '\'',
'-.--.': '(',
'-.--.-': ')',
'.-.-.': '+',
'--..--': ',',
'-....-': '-',
'.-.-.-': '.',
'-..-.': '/',
'-----': '0',
'.----': '1',
'..---': '2',
'...--': '3',
'....-': '4',
'.....': '5',
'-....': '6',
'--...': '7',
'---..': '8',
'----.': '9',
'---...': ':',
'-.-.-.': ';',
'-...-': '=',
'..--..': '?',
'.--.-.': '@',
'.-': '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',
'..--.-': '_',
'...---...': 'SOS' };