-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_029.js
53 lines (45 loc) Β· 1.09 KB
/
problem_029.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Returns the encoding of string
* @param {String} string
* @return {String}
*/
function runEncoding(string) {
if(string.length === 0) return ''
let count = 0;
let encoded = '';
let letter = string[0];
for (let i = 0; i < string.length; i++) {
currLetter = string[i];
// Check current index vs letter
if(string[i] !== letter) {
encoded = encoded + count + letter;
letter = string[i];
count = 1;
} else {
count += 1;
}
}
// Last pass
encoded = encoded + count + letter;
return encoded;
}
/**
* Returns the decoding of string
* @param {String} string
* @return {String}
*/
function runDecoding(string) {
let decoded = '';
let index = 0;
while(index < string.length) {
decoded = decoded + string[index + 1].repeat(string[index]);
index += 2;
}
return decoded;
}
console.log(runEncoding('')); // ''
console.log(runEncoding('AAA')); // '3A'
console.log(runEncoding('AAAABBBCCDAA')); // '4A3B2C1D2A'
console.log(runDecoding(''));
console.log(runDecoding('3A')); // 'AAA'
console.log(runDecoding('4A3B2C1D2A')); // 'AAAABBBCCDAA'