-
Notifications
You must be signed in to change notification settings - Fork 0
/
challenge22.ts
45 lines (40 loc) · 992 Bytes
/
challenge22.ts
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
export function compile (code: string): number {
if (code.length === 0) return 0
const codeArr: string[] = [...code]
let counter: number = 0
const santaJs: Record<string, Function> = {
'+': () => {
counter += 1
},
'-': () => {
counter -= 1
},
'*': () => {
counter *= 2
}
}
for (let i = 0; i < codeArr.length; i += 1) {
if (codeArr[i] === '<') {
const indexBackPoint = codeArr.lastIndexOf('%', i)
codeArr[i] = '#'
if (indexBackPoint !== -1) {
codeArr[indexBackPoint] = '#'
i = indexBackPoint
}
continue
}
if (codeArr[i] === '¿') {
const closeConditionIndex = codeArr.indexOf('?', i)
codeArr[i] = '#'
codeArr[closeConditionIndex] = '#'
if (counter <= 0) {
codeArr.splice(i, closeConditionIndex - 1)
i -= 1
}
continue
}
const action = santaJs[codeArr[i]]
if (action !== undefined) action()
}
return counter
}