-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge22.js
60 lines (50 loc) · 1.3 KB
/
challenge22.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
54
55
56
57
58
59
60
/*
Points: 90
OPS/S : 2929
Cognitive complexity: 14
*/
function compile(code) {
let result = 0;
let returnPointIndex = null;
let goBackIndex = null;
let shouldCompile = true;
for (let i = 0; i < code.length; i++) {
switch (code[i]) {
case '+':
if (shouldCompile) result++;
break;
case '-':
if (shouldCompile) result--;
break;
case '*':
if (shouldCompile) result *= 2;
break;
case '%':
returnPointIndex = i;
break;
case '<':
if (returnPointIndex && goBackIndex !== i) {
goBackIndex = i;
i = returnPointIndex;
}
break;
case '¿':
shouldCompile = result > 0;
break;
case '?':
shouldCompile = true;
break;
}
}
return result;
}
console.log(compile('++*-')); // 3
// (1 + 1) * 2 - 1 = 3
console.log(compile('++%++<')); // 6
// 1 + 1 + 1 + 1 + 1 + 1 = 6
console.log(compile('++<--')); // 0
// 1 + 1 - 1 - 1 = 0
console.log(compile('++¿+?')); // 3
// 1 + 1 + 1 = 3
console.log(compile('--¿+++?')); // -2
// - 1 - 1 = -2