I am working on customizing the JSON.parse
function by using the optional reviver argument
to specify that I want the calc(string)
function to focus on a key named "expr"
within the input string. Once that key is processed, the function should then operate on the remaining portion of the string.
However, whenever I run this code, I keep receiving a NaN
result.
Interestingly, if I disable the last two calls to calc(string)
just before the console.log(initNumber)
statement, the program performs as intended.
In essence, I want the function to recognize the key "expr"
and carry out specific operations based on the nested "op"
key within it. For example, if the "op"
key has a value of "add"
, the function should execute the add() function on the nested object. The same principle applies if the "op"
key is "subtract"
.
Any assistance would be greatly valued.
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);