I'm relatively new to the world of JavaScript and I'm currently working on a basic calculator that is able to read JSON strings and execute basic "add" or "subtract" operations based on them. At the moment, it can handle 1-level deep strings such as:
'{ op: 'add', number: 15 }'
This means that starting from an initial value of 0, it performs 0 + 15 resulting in an output of 15. However, my goal now is to enhance this functionality to process nested strings like the following, where "expr" indicates the beginning of a nested expression:
'{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}'
The computation for this nested string should unfold as follows: (0 - 3 = -3, -3 + (-3) = -6, -6 + (-6) = -12)
Here's the current structure of my program:
let num = 0;
class Calc {
calc(str) {
let object = JSON.parse(str);
if (object.op === "add") {
num += object.number;
} else if (object.op === "subtract") {
num -= object.number;
}
return num;
}
}
let c = new Calc();
let exp = '{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}';
// console.log(c.calc(exp));
As I progress with this project, I am contemplating how to adapt this code to support processing of even more complex, deeply nested strings spanning 3, 4, or even 5 levels.