My goal is to tell the JSON.parse
function with the optional reviver argument
that I would like it if the string being passed to the calc(string)
function has a key named "expr"
to perform the operation inside of that expression, and then continue to work outwards to operate on the rest of the string.
Every time I run this I am getting NaN
.
If I comment out the two last calc(string)
calls before console.log(initNumber)
then the program runs as expected.
So if the key is "expr"
and the value of the nested "op"
key is "add"
then perform the add() function on that nested object. Same goes for if the "op"
key is "subtract"
.
Any help is immensely appreciated.
var initNum = 0;
var calc = function(string) {
var calcString = JSON.parse(string, reviver);
add(calcString);
subtract(calcString);
};
var add = function(string) {
if (string["op"] == "add") {
var numString = parseInt(JSON.stringify(string["number"]));
initNum = numString + initNum;
return initNum;
}
}
var subtract = function(string) {
if (string["op"] == "subtract") {
var numString = parseInt(JSON.stringify(string["number"]));
initNum = initNum - numString;
return initNum;
}
}
var reviver = function(key, val) {
if (key == "expr") {
if (val.op == "add") {
return add(val);
}
else if (val.op == "subtract") {
return subtract(val);
}
}
else {
return val;
}
};
calc('{"op" : "add", "number" : 5}');
calc('{"op" : "subtract", "number" : 2}');
calc('{"op" : "add", "number" : 19}');
calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
calc('{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}');
console.log(initNum);