Reputation: 123
I'm trying to write a recursive function that, if it contains "expr" as a key instead of "number" it will feed that section of the JSON back into the function. My code is the following:
var result = 0;
function calc(str) {
var obj = JSON.parse(str);
if(obj.hasOwnProperty("expr")) {
var temp = obj.expr;
JSON.stringify(temp);
calc(temp);
}
if (obj.op == "add") {
var i = parseInt(obj.number);
result += i;
} else if(obj.op == "subtract") {
var i = parseInt(obj.number);
result -= i;
}
return result;
}
I'm getting a Syntax Error saying "Unexpected token o in JSON at position 1." Does Stringify not reformat it back into a string? If so, how would I go about that?
My input is something like the following:
result = calc('{"op" : "add", "number" : 5}');
result = calc('{"op" : "subtract", "number" : 2}');
result = calc('{"op" : "add", "number" : 19}');
result = calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
Upvotes: 0
Views: 1471
Reputation: 123
I got it figured out.
var result = 0;
function calc(str) {
var obj = JSON.parse(str);
var i = parseInt(obj.number);
if(obj.hasOwnProperty("expr")) {
var temp = obj.expr;
temp = JSON.stringify(temp);
var i = calc(temp);
}
if (obj.op == "add") {
result += i;
} else if(obj.op == "subtract") {
result -= i;
}
return result;
}
Upvotes: 0
Reputation: 2463
Should be like this:
function calc(str) {
var res = 0;
var obj = (typeof str =="string") ? JSON.parse(str) : str;
if(obj.hasOwnProperty("expr")) obj.number = calc(obj.expr);
switch(obj.op){
case "add":
res += +obj.number;
break;
case "subtract":
res -= +obj.number;
break;
}
return res;
}
Input
var result = 0;
result += calc('{"op" : "add", "number" : 5}');
result += calc('{"op" : "subtract", "number" : 2}');
result += calc('{"op" : "add", "number" : 19}');
result += calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
Upvotes: 1