I'm pretty new to JS and am trying to work on a basic calculator that reads in JSON strings and performs basic "add" or "subtract" operations on them. Currently, it can process 1-level deep strings like so:
'{ op: 'add', number: 15 }'
Where the initial value is 0 and will perform 0+15 so the output is 15. What I am trying to do now, is make the same function process a nested string like so where "expr" denotes that start of a nested expression:
'{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}'
And the operation should go like this: (0-3= -3, -3+-3= -6, -6+-6= -12)
My current program is as follows:
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));
How can I modify this to further handle even 3,4,5 levels nested strings?