-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path(4 kyu) Decode the Morse code, advanced.js
More file actions
47 lines (44 loc) · 1.06 KB
/
(4 kyu) Decode the Morse code, advanced.js
File metadata and controls
47 lines (44 loc) · 1.06 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
const decodeBits = (bits) => {
const arrayOfBits = bits.match(/(\d)\1*/g); // split for parts
// find the length of symbols
const length = Math.min(
Infinity,
...arrayOfBits
.filter(
(
x,
i, // remove some extra 0's
) =>
(i === 0 && x[0] === '1') ||
(i > 0 && i < arrayOfBits.length - 1) ||
(i === arrayOfBits.length - 1 && x[0] === '1'),
)
.map((x) => x.length),
);
return arrayOfBits.map((x) => {
const symLength = x.length / length; // find the correct length
return +x[0] // decode bits to Morse code
? symLength > 1
? '-'
: '.'
: symLength > 3
? ' '
: symLength > 1
? ' '
: '';
}).join``;
};
const decodeMorse = (morseCode) => {
return morseCode
.trim() //remove extra spaces
.split(' ') //devide by words
.map((
str, //parse each word
) =>
str
.split(' ') //devide by symbols
.map((s) => MORSE_CODE[s]) //return Char
.join(''),
)
.join(' ');
};