-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavascript.js
95 lines (95 loc) · 2.72 KB
/
Javascript.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
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
let spreadsheet = [];
let indexNotCalculated = []; //all index of spreadsheet not calculated
const N = parseInt(readline());
for (let i = 0; i < N; i++) {
var inputs = readline().split(" ");
let object = {
operation: inputs[0],
arg1: inputs[1],
arg2: inputs[2],
value: null,
};
if (canProcess(object, i)) {
//Check if we can calcul and calcul if true
object.value = process(object);
} else {
//If we cant calcul add the index in indexNotCalculated
indexNotCalculated.push(i);
}
spreadsheet.push(object);
}
let index = 0;
while (indexNotCalculated.length != 0) {
let object = spreadsheet[indexNotCalculated[index]];
if (canProcess(object)) {
//Check if we can calcul
object.value = process(object); //calcul
indexNotCalculated.splice(index, 1); //delete index in indexNotCalculated
index = 0; //reset actuel index (of array indexNotCalculated) check
} else {
index++; //increase index (of array indexNotCalculated)
}
}
for (let i = 0; i < N; i++) {
console.log(spreadsheet[i].value);
}
function process(object) {
let valueArg1 = parseInt(object.arg1[0] == "$" ? spreadsheet[parseInt(object.arg1.substring(1))].value : object.arg1); //Get the value of arg1
let valueArg2 = parseInt(object.arg2[0] == "$" ? spreadsheet[parseInt(object.arg2.substring(1))].value : object.arg2); //Get the value of arg2
let answer = 0;
switch (object.operation) {
case "VALUE":
answer = valueArg1;
break;
case "ADD":
answer = valueArg1 + valueArg2;
break;
case "SUB":
answer = valueArg1 - valueArg2;
break;
case "MULT":
answer = valueArg1 * valueArg2;
break;
}
if (answer === -0) {
answer = 0;
}
return answer;
}
function canProcess(object, i = -1) {
let argIsRef = [false, false];
let process = true;
if (object.arg1[0] == "$") {
argIsRef[0] = true;
}
if (object.arg2[0] == "$") {
argIsRef[1] = true;
}
if (argIsRef[0] || argIsRef[1]) {
if (argIsRef[0]) {
//Arg1 is ref
let indexRef = parseInt(object.arg1.substring(1));
if (indexRef < i || i == -1) {
//Check if ths index of the ref has been checked
if (indexNotCalculated.includes(indexRef)) {
process = false;
} //Check if the ref is in indexNotCalculated
} else {
process = false;
}
}
if (argIsRef[1]) {
//Arg2 is ref
let indexRef = parseInt(object.arg2.substring(1));
if (indexRef < i || i == -1) {
//Check if ths index of the ref has been checked
if (indexNotCalculated.includes(indexRef)) {
process = false;
} //Check if the ref is in indexNotCalculated
} else {
process = false;
}
}
}
return process;
}